index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/CompatibilityTest.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import com.netflix.spectator.compat.Main; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; /** * Pulls in a small test class that uses most of the public api and was compiled with a previous * version. It isn't automatically updated, but is simple and catches some of the more egregious * compatibility issues that were sometimes missed by the compatibility check task on the build. */ public class CompatibilityTest { private static List<String> EXPECTED = new ArrayList<>(); static { EXPECTED.add("Measurement(bucket-counter-age:bucket=062ms,1234567890,63.0)"); EXPECTED.add("Measurement(bucket-counter-age:bucket=125ms,1234567890,63.0)"); EXPECTED.add("Measurement(bucket-counter-age:bucket=250ms,1234567890,125.0)"); EXPECTED.add("Measurement(bucket-counter-age:bucket=500ms,1234567890,250.0)"); EXPECTED.add("Measurement(bucket-counter-age:bucket=old,1234567890,499.0)"); EXPECTED.add("Measurement(bucket-counter-ageBiasOld:bucket=250ms,1234567890,251.0)"); EXPECTED.add("Measurement(bucket-counter-ageBiasOld:bucket=375ms,1234567890,125.0)"); EXPECTED.add("Measurement(bucket-counter-ageBiasOld:bucket=437ms,1234567890,62.0)"); EXPECTED.add("Measurement(bucket-counter-ageBiasOld:bucket=500ms,1234567890,63.0)"); EXPECTED.add("Measurement(bucket-counter-ageBiasOld:bucket=old,1234567890,499.0)"); EXPECTED.add("Measurement(bucket-counter-bytes:bucket=062_B,1234567890,1.0)"); EXPECTED.add("Measurement(bucket-counter-bytes:bucket=large,1234567890,999.0)"); EXPECTED.add("Measurement(bucket-counter-decimal:bucket=062,1234567890,1.0)"); EXPECTED.add("Measurement(bucket-counter-decimal:bucket=large,1234567890,999.0)"); EXPECTED.add("Measurement(bucket-counter-latency:bucket=062ms,1234567890,63.0)"); EXPECTED.add("Measurement(bucket-counter-latency:bucket=125ms,1234567890,63.0)"); EXPECTED.add("Measurement(bucket-counter-latency:bucket=250ms,1234567890,125.0)"); EXPECTED.add("Measurement(bucket-counter-latency:bucket=500ms,1234567890,250.0)"); EXPECTED.add("Measurement(bucket-counter-latency:bucket=slow,1234567890,499.0)"); EXPECTED.add("Measurement(bucket-counter-latencyBiasSlow:bucket=062ms,1234567890,63.0)"); EXPECTED.add("Measurement(bucket-counter-latencyBiasSlow:bucket=125ms,1234567890,63.0)"); EXPECTED.add("Measurement(bucket-counter-latencyBiasSlow:bucket=250ms,1234567890,125.0)"); EXPECTED.add("Measurement(bucket-counter-latencyBiasSlow:bucket=500ms,1234567890,250.0)"); EXPECTED.add("Measurement(bucket-counter-latencyBiasSlow:bucket=slow,1234567890,499.0)"); EXPECTED.add("Measurement(bucket-dist:bucket=250ms:statistic=count,1234567890,251.0)"); EXPECTED.add("Measurement(bucket-dist:bucket=250ms:statistic=totalAmount,1234567890,3.1375E10)"); EXPECTED.add("Measurement(bucket-dist:bucket=375ms:statistic=count,1234567890,125.0)"); EXPECTED.add("Measurement(bucket-dist:bucket=375ms:statistic=totalAmount,1234567890,3.9125E10)"); EXPECTED.add("Measurement(bucket-dist:bucket=437ms:statistic=count,1234567890,62.0)"); EXPECTED.add("Measurement(bucket-dist:bucket=437ms:statistic=totalAmount,1234567890,2.5203E10)"); EXPECTED.add("Measurement(bucket-dist:bucket=500ms:statistic=count,1234567890,63.0)"); EXPECTED.add("Measurement(bucket-dist:bucket=500ms:statistic=totalAmount,1234567890,2.9547E10)"); EXPECTED.add("Measurement(bucket-dist:bucket=slow:statistic=count,1234567890,499.0)"); EXPECTED.add("Measurement(bucket-dist:bucket=slow:statistic=totalAmount,1234567890,3.7425E11)"); EXPECTED.add("Measurement(bucket-timer:bucket=062ms:statistic=count,1234567890,63.0)"); EXPECTED.add("Measurement(bucket-timer:bucket=062ms:statistic=totalTime,1234567890,1.953E9)"); EXPECTED.add("Measurement(bucket-timer:bucket=125ms:statistic=count,1234567890,63.0)"); EXPECTED.add("Measurement(bucket-timer:bucket=125ms:statistic=totalTime,1234567890,5.922E9)"); EXPECTED.add("Measurement(bucket-timer:bucket=250ms:statistic=count,1234567890,125.0)"); EXPECTED.add("Measurement(bucket-timer:bucket=250ms:statistic=totalTime,1234567890,2.35E10)"); EXPECTED.add("Measurement(bucket-timer:bucket=500ms:statistic=count,1234567890,250.0)"); EXPECTED.add("Measurement(bucket-timer:bucket=500ms:statistic=totalTime,1234567890,9.3875E10)"); EXPECTED.add("Measurement(bucket-timer:bucket=old:statistic=count,1234567890,499.0)"); EXPECTED.add("Measurement(bucket-timer:bucket=old:statistic=totalTime,1234567890,3.7425E11)"); EXPECTED.add("Measurement(collection-size,1234567890,8.0)"); EXPECTED.add("Measurement(counter,1234567890,127.0)"); EXPECTED.add("Measurement(counter:a=b,1234567890,381.0)"); EXPECTED.add("Measurement(dist:a=b:statistic=count,1234567890,15.0)"); EXPECTED.add("Measurement(dist:a=b:statistic=totalAmount,1234567890,504.0)"); EXPECTED.add("Measurement(dist:statistic=count,1234567890,5.0)"); EXPECTED.add("Measurement(dist:statistic=totalAmount,1234567890,168.0)"); EXPECTED.add("Measurement(gauge,1234567890,49.0)"); EXPECTED.add("Measurement(gauge-active:a=0,1234567890,1.0)"); EXPECTED.add("Measurement(gauge-active:a=1,1234567890,2.0)"); EXPECTED.add("Measurement(gauge-active:a=2,1234567890,3.0)"); EXPECTED.add("Measurement(gauge-age,1234567890,0.049)"); EXPECTED.add("Measurement(gauge-function,1234567890,65.0)"); EXPECTED.add("Measurement(gauge-polled:type=collection-size,1234567890,1.0)"); EXPECTED.add("Measurement(gauge-polled:type=map-size,1234567890,1.0)"); EXPECTED.add("Measurement(gauge-polled:type=remove,1234567890,NaN)"); EXPECTED.add("Measurement(gauge-polled:type=value,1234567890,42.0)"); EXPECTED.add("Measurement(gauge-polled:type=value-function,1234567890,84.0)"); EXPECTED.add("Measurement(gauge-polled:type=value-monotonic,1234567890,0.0)"); EXPECTED.add("Measurement(gauge-polled:type=value-monotonic-function,1234567890,0.0)"); EXPECTED.add("Measurement(gauge:app=foo:asg=foo-dev-v001:cluster=foo-dev:node=i-12345,1234567890,7.0)"); EXPECTED.add("Measurement(long-timer:a=b:statistic=activeTasks,1234567890,3.0)"); EXPECTED.add("Measurement(long-timer:a=b:statistic=duration,1234567890,15120.0)"); EXPECTED.add("Measurement(long-timer:statistic=activeTasks,1234567890,1.0)"); EXPECTED.add("Measurement(long-timer:statistic=duration,1234567890,10080.0)"); EXPECTED.add("Measurement(map-size,1234567890,8.0)"); EXPECTED.add("Measurement(method-value,1234567890,22.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D0000:statistic=percentile,1234567890,1.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D0056:statistic=percentile,1234567890,1.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D0059:statistic=percentile,1234567890,1.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D005C:statistic=percentile,1234567890,1.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D005F:statistic=percentile,1234567890,1.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D0060:statistic=percentile,1234567890,1.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D0061:statistic=percentile,1234567890,1.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D0062:statistic=percentile,1234567890,2.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D0063:statistic=percentile,1234567890,1.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D0064:statistic=percentile,1234567890,2.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D0065:statistic=percentile,1234567890,1.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D0066:statistic=percentile,1234567890,1.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D0067:statistic=percentile,1234567890,2.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D0068:statistic=percentile,1234567890,1.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D0069:statistic=percentile,1234567890,6.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D006A:statistic=percentile,1234567890,5.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D006B:statistic=percentile,1234567890,6.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D006C:statistic=percentile,1234567890,6.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D006D:statistic=percentile,1234567890,5.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D006E:statistic=percentile,1234567890,6.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D006F:statistic=percentile,1234567890,5.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D0070:statistic=percentile,1234567890,6.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D0071:statistic=percentile,1234567890,6.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D0072:statistic=percentile,1234567890,22.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D0073:statistic=percentile,1234567890,22.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D0074:statistic=percentile,1234567890,23.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D0075:statistic=percentile,1234567890,22.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D0076:statistic=percentile,1234567890,22.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D0077:statistic=percentile,1234567890,23.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D0078:statistic=percentile,1234567890,22.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D0079:statistic=percentile,1234567890,23.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D007A:statistic=percentile,1234567890,22.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D007B:statistic=percentile,1234567890,89.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D007C:statistic=percentile,1234567890,90.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D007D:statistic=percentile,1234567890,89.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D007E:statistic=percentile,1234567890,90.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D007F:statistic=percentile,1234567890,89.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D0080:statistic=percentile,1234567890,90.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D0081:statistic=percentile,1234567890,89.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D0082:statistic=percentile,1234567890,90.0)"); EXPECTED.add("Measurement(percentile-dist:percentile=D0083:statistic=percentile,1234567890,15.0)"); EXPECTED.add("Measurement(percentile-dist:statistic=count,1234567890,1000.0)"); EXPECTED.add("Measurement(percentile-dist:statistic=totalAmount,1234567890,4.995E11)"); EXPECTED.add("Measurement(percentile-timer:percentile=T0000:statistic=percentile,1234567890,1.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T0056:statistic=percentile,1234567890,1.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T0059:statistic=percentile,1234567890,1.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T005C:statistic=percentile,1234567890,1.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T005F:statistic=percentile,1234567890,1.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T0060:statistic=percentile,1234567890,1.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T0061:statistic=percentile,1234567890,1.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T0062:statistic=percentile,1234567890,2.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T0063:statistic=percentile,1234567890,1.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T0064:statistic=percentile,1234567890,2.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T0065:statistic=percentile,1234567890,1.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T0066:statistic=percentile,1234567890,1.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T0067:statistic=percentile,1234567890,2.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T0068:statistic=percentile,1234567890,1.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T0069:statistic=percentile,1234567890,6.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T006A:statistic=percentile,1234567890,5.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T006B:statistic=percentile,1234567890,6.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T006C:statistic=percentile,1234567890,6.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T006D:statistic=percentile,1234567890,5.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T006E:statistic=percentile,1234567890,6.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T006F:statistic=percentile,1234567890,5.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T0070:statistic=percentile,1234567890,6.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T0071:statistic=percentile,1234567890,6.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T0072:statistic=percentile,1234567890,22.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T0073:statistic=percentile,1234567890,22.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T0074:statistic=percentile,1234567890,23.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T0075:statistic=percentile,1234567890,22.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T0076:statistic=percentile,1234567890,22.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T0077:statistic=percentile,1234567890,23.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T0078:statistic=percentile,1234567890,22.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T0079:statistic=percentile,1234567890,23.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T007A:statistic=percentile,1234567890,22.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T007B:statistic=percentile,1234567890,89.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T007C:statistic=percentile,1234567890,90.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T007D:statistic=percentile,1234567890,89.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T007E:statistic=percentile,1234567890,90.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T007F:statistic=percentile,1234567890,89.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T0080:statistic=percentile,1234567890,90.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T0081:statistic=percentile,1234567890,89.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T0082:statistic=percentile,1234567890,90.0)"); EXPECTED.add("Measurement(percentile-timer:percentile=T0083:statistic=percentile,1234567890,15.0)"); EXPECTED.add("Measurement(percentile-timer:statistic=count,1234567890,1000.0)"); EXPECTED.add("Measurement(percentile-timer:statistic=totalTime,1234567890,4.995E11)"); EXPECTED.add("Measurement(threadpool.completedTaskCount:id=test-pool,1234567890,0.0)"); EXPECTED.add("Measurement(threadpool.corePoolSize:id=test-pool,1234567890,2.0)"); EXPECTED.add("Measurement(threadpool.currentThreadsBusy:id=test-pool,1234567890,0.0)"); EXPECTED.add("Measurement(threadpool.maxThreads:id=test-pool,1234567890,2.147483647E9)"); EXPECTED.add("Measurement(threadpool.poolSize:id=test-pool,1234567890,0.0)"); EXPECTED.add("Measurement(threadpool.queueSize:id=test-pool,1234567890,0.0)"); EXPECTED.add("Measurement(threadpool.rejectedTaskCount:id=test-pool,1234567890,0.0)"); EXPECTED.add("Measurement(threadpool.taskCount:id=test-pool,1234567890,0.0)"); EXPECTED.add("Measurement(timer:a=b:statistic=count,1234567890,24.0)"); EXPECTED.add("Measurement(timer:a=b:statistic=totalTime,1234567890,4.53852000126E14)"); EXPECTED.add("Measurement(timer:statistic=count,1234567890,8.0)"); EXPECTED.add("Measurement(timer:statistic=totalTime,1234567890,1.51284000042E14)"); } @Test public void check() throws Exception { List<String> actual = new ArrayList<>(Main.run()); //for (String s : actual) { // System.out.println(" EXPECTED.add(\"" + s + "\");"); //} int length = Math.max(EXPECTED.size(), actual.size()); for (int i = 0; i < length; ++i) { String exp = (i < EXPECTED.size()) ? EXPECTED.get(i) : null; String found = (i < actual.size()) ? actual.get(i) : null; Assertions.assertEquals(exp, found); } } }
5,700
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/BasicTagTest.java
/* * Copyright 2014-2021 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Unit tests for the BasicTag class. */ public class BasicTagTest { @Test public void equalsContractTest() { // NOTE: EqualsVerifier doesn't work with cached hash code final BasicTag tag1 = new BasicTag("k1", "v1"); BasicTag tag2 = new BasicTag("k2", "v2"); Assertions.assertEquals(tag1, tag1); Assertions.assertEquals(tag2, tag2); Assertions.assertNotEquals(tag1, tag2); Assertions.assertNotEquals(tag1, null); Assertions.assertNotEquals(tag1, new Object()); Assertions.assertNotEquals(tag1, new BasicTag("k1", "v2")); Assertions.assertNotEquals(tag1, new BasicTag("k2", "v1")); Assertions.assertNotEquals(tag1, new Tag() { @Override public String key() { return tag1.key(); } @Override public String value() { return tag1.value(); } }); } @Test public void testHashCode() { BasicTag tag = new BasicTag("k1", "v1"); Assertions.assertEquals(tag.hashCode(), new BasicTag(tag.key(), tag.value()).hashCode()); } @Test public void testToString() { BasicTag tag = new BasicTag("k1", "v1"); Assertions.assertEquals("k1=v1", tag.toString()); } @Test public void testAccessors() { BasicTag tag = new BasicTag("k", "v"); Assertions.assertEquals(tag.key(), "k"); Assertions.assertEquals(tag.value(), "v"); } @Test public void testNullKey() { Assertions.assertThrows(NullPointerException.class, () -> new BasicTag(null, "v")); } @Test public void testNullValue() { NullPointerException e = Assertions.assertThrows( NullPointerException.class, () -> new BasicTag("k", null)); Assertions.assertEquals("parameter 'value' cannot be null (key=k)", e.getMessage()); } }
5,701
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/DefaultIdTest.java
/* * Copyright 2014-2020 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.nio.file.AccessMode; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.Spliterator; public class DefaultIdTest { @Test public void testNullName() { Assertions.assertThrows(NullPointerException.class, () -> new DefaultId(null)); } @Test public void testName() { Id id = new DefaultId("foo"); Assertions.assertEquals(id.name(), "foo"); } @Test public void testTags() { ArrayTagSet ts = ArrayTagSet.create("k1", "v1"); Id id = new DefaultId("foo", ts); Assertions.assertEquals(id.name(), "foo"); Assertions.assertEquals(id.tags(), ts); } @Test public void testTagsEmpty() { Id id = new DefaultId("foo"); Assertions.assertFalse(id.tags().iterator().hasNext()); } @Test public void equalsContractTest() { ArrayTagSet ts1 = ArrayTagSet.create("k1", "v1"); ArrayTagSet ts2 = ArrayTagSet.create("k2", "v2").addAll(ts1); EqualsVerifier .forClass(DefaultId.class) .withPrefabValues(ArrayTagSet.class, ts1, ts2) .suppress(Warning.NULL_FIELDS) .verify(); } @Test public void testNormalize() { DefaultId id12 = (new DefaultId("foo")).withTag("k1", "v1").withTag("k2", "v2"); DefaultId id21 = (new DefaultId("foo")).withTag("k1", "v1").withTags(id12.tags()); Assertions.assertEquals(id12, id21); Assertions.assertEquals(id12, id21.normalize()); } @Test public void testRollup() { Set<String> keys = new HashSet<>(); keys.add("k1"); keys.add("foo"); DefaultId id = (new DefaultId("foo")).withTag("k1", "v1").withTag("k2", "v2"); DefaultId keepId = (new DefaultId("foo")).withTag("k1", "v1"); DefaultId dropId = (new DefaultId("foo")).withTag("k2", "v2"); Assertions.assertEquals(keepId, id.rollup(keys, true)); Assertions.assertEquals(dropId, id.rollup(keys, false)); } @Test public void testRollupJustName() { DefaultId id = new DefaultId("foo"); Assertions.assertSame(id, id.normalize()); } @Test public void testRollupDeduping() { Set<String> keys = new HashSet<>(); keys.add("k1"); DefaultId idWithDupes = (new DefaultId("foo")).withTag("k1", "v1").withTag("k1", "v2"); DefaultId expectedId = (new DefaultId("foo")).withTag("k1", "v2"); Assertions.assertEquals(expectedId, idWithDupes.rollup(keys, true)); } @Test public void testRollupDedupingOfExcludedKey() { Set<String> keys = new HashSet<>(); keys.add("k1"); DefaultId idWithDupes = (new DefaultId("foo")).withTag("k1", "v1").withTag("k1", "v2"); DefaultId expectedId = new DefaultId("foo"); Assertions.assertEquals(expectedId, idWithDupes.rollup(keys, false)); } @Test public void testToString() { DefaultId id = (new DefaultId("foo")).withTag("k1", "v1").withTag("k2", "v2"); Assertions.assertEquals("foo:k1=v1:k2=v2", id.toString()); } @Test public void testToStringNameOnly() { DefaultId id = new DefaultId("foo"); Assertions.assertEquals(id.toString(), "foo"); } @Test public void testWithTagsMap() { Map<String, String> map = new LinkedHashMap<>(); map.put("k1", "v1"); map.put("k2", "v2"); DefaultId id = (new DefaultId("foo")).withTags(map); Assertions.assertEquals("foo:k1=v1:k2=v2", id.toString()); } @Test public void addTagAppend() { Id id = new DefaultId("TotalTime") .withTag("app", "foo") .withTag("exception.thrown", "pvr"); Assertions.assertEquals("TotalTime:app=foo:exception.thrown=pvr", id.toString()); } @Test public void addTagPrepend() { Id id = new DefaultId("TotalTime") .withTag("app", "foo") .withTag("aaa", "pvr"); Assertions.assertEquals("TotalTime:aaa=pvr:app=foo", id.toString()); } @Test public void addTagInsert() { Id id = new DefaultId("TotalTime") .withTag("app", "foo") .withTag("exception.thrown", "pvr") .withTag("bbb", "bar"); Assertions.assertEquals("TotalTime:app=foo:bbb=bar:exception.thrown=pvr", id.toString()); } @Test public void dedupAndAppend() { Id id = new DefaultId("TotalTime") .withTag("app", "foo") .withTags("app", "foo") .withTag("exception.thrown", "pvr"); Assertions.assertEquals("TotalTime:app=foo:exception.thrown=pvr", id.toString()); } @Test public void withTagBooleanTrue() { Id id = new DefaultId("test").withTag("bool", true); Assertions.assertEquals("test:bool=true", id.toString()); Assertions.assertEquals(new DefaultId("test").withTag("bool", "true"), id); } @Test public void withTagBooleanFalse() { Id id = new DefaultId("test").withTag("bool", false); Assertions.assertEquals("test:bool=false", id.toString()); Assertions.assertEquals(new DefaultId("test").withTag("bool", "false"), id); } @Test public void withTagBooleanObjFalse() { Id id = new DefaultId("test").withTag("bool", Boolean.FALSE); Assertions.assertEquals("test:bool=false", id.toString()); Assertions.assertEquals(new DefaultId("test").withTag("bool", "false"), id); } @Test public void withTagBooleanObjNull() { Assertions.assertThrows(NullPointerException.class, () -> { Boolean value = null; new DefaultId("test").withTag("bool", value); }); } @Test public void withTagEnum() { Id id = new DefaultId("test").withTag("enum", AccessMode.WRITE); Assertions.assertEquals("test:enum=WRITE", id.toString()); Assertions.assertEquals(new DefaultId("test").withTag("enum", "WRITE"), id); } @Test public void withTagEnumNull() { Assertions.assertThrows(NullPointerException.class, () -> { Enum<?> value = null; new DefaultId("test").withTag("enum", value); }); } @Test public void issue483() { // Before calling hashCode on this id caused NPE Id id1 = new DefaultId("test") .withTag("api_name", "foo") .withTags(Statistic.percentile, new BasicTag("percentile", "1")); // Forces deduping to improve coverage Id id2 = new DefaultId("test") .withTag("api_name", "foo") .withTags( Statistic.percentile, new BasicTag("percentile", "2"), Statistic.percentile, new BasicTag("percentile", "1")); Assertions.assertEquals(id1.hashCode(), id2.hashCode()); Assertions.assertEquals(id1, id2); } @Test public void issue483_2() { // Another sanity check using the full key set Id id1 = new DefaultId("test") .withTag("api_name", "foo") .withTag("api_partner", "3") .withTag("api_status", "failed") .withTag("api_http_code", "400") .withTag("api_error_code", "BadRequest") .withTags(Statistic.percentile, new BasicTag("percentile", "1")); // Forces deduping to improve coverage Id id2 = new DefaultId("test") .withTag("api_name", "foo") .withTag("api_partner", "3") .withTag("api_status", "failed") .withTag("api_http_code", "400") .withTag("api_error_code", "BadRequest") .withTags( Statistic.percentile, new BasicTag("percentile", "2"), Statistic.percentile, new BasicTag("percentile", "1")); Assertions.assertEquals(id1.hashCode(), id2.hashCode()); Assertions.assertEquals(id1, id2); } @Test public void tagListIterator() { List<Tag> expected = new ArrayList<>(); expected.add(Tag.of("name", "foo")); expected.add(Tag.of("k1", "v1")); expected.add(Tag.of("k2", "v2")); DefaultId id = (new DefaultId("foo")).withTag("k1", "v1").withTag("k2", "v2"); List<Tag> actual = new ArrayList<>(); for (Tag t : id) { actual.add(t); } Assertions.assertEquals(expected, actual); } @Test public void tagListForEach() { List<Tag> expected = new ArrayList<>(); expected.add(Tag.of("name", "foo")); expected.add(Tag.of("k1", "v1")); expected.add(Tag.of("k2", "v2")); DefaultId id = (new DefaultId("foo")).withTag("k1", "v1").withTag("k2", "v2"); List<Tag> actual = new ArrayList<>(); id.forEach((k, v) -> actual.add(Tag.of(k, v))); Assertions.assertEquals(expected, actual); } @Test public void tagListFilter() { DefaultId id = new DefaultId("foo", ArrayTagSet.create("a", "1", "b", "2")); Id expected = Id.create("foo").withTag("a", "1"); Assertions.assertEquals(expected, id.filter((k, v) -> !k.equals("b"))); } @Test public void tagListFilterByKey() { DefaultId id = new DefaultId("foo", ArrayTagSet.create("a", "1", "b", "2")); Id expected = Id.create("foo").withTag("a", "1"); Assertions.assertEquals(expected, id.filterByKey(k -> !k.equals("b"))); } @Test public void tagListFilterByKeyName() { // Name is required and is ignored for filtering DefaultId id = new DefaultId("foo", ArrayTagSet.create("a", "1", "b", "2")); Assertions.assertEquals(id, id.filterByKey(k -> !k.equals("name"))); } @Test public void compareToEquals() { Id a = Id.create("foo").withTags("a", "1", "b", "2"); Id b = Id.create("foo").withTags("a", "1", "b", "2"); Assertions.assertEquals(0, a.compareTo(b)); } @Test public void compareToDifferentName() { Id a = Id.create("foo").withTags("a", "1", "b", "2"); Id b = Id.create("bar").withTags("a", "1", "b", "2"); Assertions.assertEquals(4, a.compareTo(b)); Assertions.assertEquals(-4, b.compareTo(a)); } @Test public void compareToDifferentKey() { Id a = Id.create("foo").withTags("a", "1", "b", "2"); Id b = Id.create("foo").withTags("a", "1", "d", "2"); Assertions.assertEquals(-2, a.compareTo(b)); Assertions.assertEquals(2, b.compareTo(a)); } @Test public void compareToDifferentValue() { Id a = Id.create("foo").withTags("a", "1", "b", "3"); Id b = Id.create("foo").withTags("a", "1", "b", "2"); Assertions.assertEquals(1, a.compareTo(b)); Assertions.assertEquals(-1, b.compareTo(a)); } private String randomString(Random r) { return "" + ((char) (r.nextInt(26) + 'a')); } private Id randomId(Random r) { Id id = Id.create(randomString(r)); int n = r.nextInt(10); for (int i = 0; i < n; ++i) { id = id.withTag(randomString(r), randomString(r)); } return id; } private int normalize(int cmp) { // Force comparison values to be: -1, 0, or 1. return Integer.compare(cmp, 0); } @Test public void compareToMatchesToStringOrder() { Random r = new Random(42); for (int i = 0; i < 10_000; ++i) { Id id1 = randomId(r); Id id2 = randomId(r); Assertions.assertEquals(0, id1.compareTo(id1)); Assertions.assertEquals(0, id2.compareTo(id2)); int strCmp = normalize(id1.toString().compareTo(id2.toString())); int idCmp = normalize(id1.compareTo(id2)); Assertions.assertEquals(strCmp, idCmp); } } @Test public void unsafeCreate() { Id id = Id.unsafeCreate("foo", new String[] {"k2", "v2", "k1", "v1", null, null}, 4); Id expected = Id.create("foo").withTags("k2", "v2", "k1", "v1"); Assertions.assertEquals(expected, id); } @Test public void unsafeCreateDuplicates() { Id id = Id.unsafeCreate("foo", new String[] {"k1", "_", "k2", "v2", "k1", "v1", null, null}, 6); Id expected = Id.create("foo").withTags("k1", "_", "k1", "v1", "k2", "v2"); Assertions.assertEquals(expected, id); } @Test public void spliteratorSizeAndCharacteristics() { Id id = Id.create("foo").withTags("k1", "v1", "k2", "v2"); Spliterator<Tag> spliterator = id.spliterator(); Assertions.assertTrue(spliterator.hasCharacteristics(Spliterator.ORDERED)); Assertions.assertTrue(spliterator.hasCharacteristics(Spliterator.SIZED)); Assertions.assertEquals(3, spliterator.getExactSizeIfKnown()); } }
5,702
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/RegistryTest.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import com.netflix.spectator.api.patterns.PolledMeter; import com.netflix.spectator.impl.SwapMeter; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Collections; import java.util.DoubleSummaryStatistics; import java.util.LinkedHashMap; import java.util.List; import java.util.LongSummaryStatistics; import java.util.Map; import java.util.Spliterator; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.function.ToDoubleFunction; import java.util.stream.Collectors; public class RegistryTest { private final ManualClock clock = new ManualClock(); private DefaultRegistry newRegistry(boolean warnings, int numberOfMeters) { return new DefaultRegistry(clock, new TestRegistryConfig(warnings, numberOfMeters)); } @Test public void testCreateIdArray() { Registry r = newRegistry(true, 10000); Id id1 = r.createId("foo", "bar", "baz", "k", "v"); Id id2 = r.createId("foo", ArrayTagSet.create("k", "v").add(new BasicTag("bar", "baz"))); Assertions.assertEquals(id1, id2); } @Test public void testCreateIdArrayOdd() { Assertions.assertThrows(IllegalArgumentException.class, () -> { Registry r = newRegistry(true, 10000); r.createId("foo", "bar", "baz", "k"); }); } @Test public void testCreateIdMap() { Map<String, String> map = new LinkedHashMap<>(); map.put("k1", "v1"); map.put("k2", "v2"); Registry r = newRegistry(true, 10000); Id id1 = r.createId("foo", map); Id id2 = r.createId("foo", "k1", "v1", "k2", "v2"); Assertions.assertEquals(id1, id2); } private Object unwrap(Object obj) { if (obj instanceof SwapMeter<?>) { return ((SwapMeter<?>) obj).get(); } return obj; } @Test public void testCounterHelpers() { Registry r = newRegistry(true, 10000); Counter c1 = r.counter("foo", "bar", "baz", "k", "v"); Counter c2 = r.counter("foo", ArrayTagSet.create("k", "v").add(new BasicTag("bar", "baz"))); Counter c3 = r.counter("foo"); Assertions.assertSame(unwrap(c1), unwrap(c2)); Assertions.assertNotSame(unwrap(c1), unwrap(c3)); } @Test public void testDistributionSummaryHelpers() { Registry r = newRegistry(true, 10000); DistributionSummary c1 = r.distributionSummary("foo", "bar", "baz", "k", "v"); DistributionSummary c2 = r.distributionSummary("foo", ArrayTagSet.create("k", "v").add(new BasicTag("bar", "baz"))); DistributionSummary c3 = r.distributionSummary("foo"); Assertions.assertSame(unwrap(c1), unwrap(c2)); Assertions.assertNotSame(unwrap(c1), unwrap(c3)); } @Test public void testTimerHelpers() { Registry r = newRegistry(true, 10000); Timer c1 = r.timer("foo", "bar", "baz", "k", "v"); Timer c2 = r.timer("foo", ArrayTagSet.create("k", "v").add(new BasicTag("bar", "baz"))); Timer c3 = r.timer("foo"); Assertions.assertSame(unwrap(c1), unwrap(c2)); Assertions.assertNotSame(unwrap(c1), unwrap(c3)); } private void assertLongTaskTimer(Registry r, Id id, long timestamp, int activeTasks, double duration) { PolledMeter.update(r); Gauge g = r.gauge(id.withTag(Statistic.activeTasks)); Assertions.assertEquals(timestamp, g.measure().iterator().next().timestamp()); Assertions.assertEquals(activeTasks, g.value(), 1.0e-12); g = r.gauge(id.withTag(Statistic.duration)); Assertions.assertEquals(timestamp, g.measure().iterator().next().timestamp()); Assertions.assertEquals(duration, g.value(), 1.0e-12); } @Test public void testLongTaskTimerHelpers() { ManualClock clock = new ManualClock(); Registry r = new DefaultRegistry(clock); LongTaskTimer c1 = r.longTaskTimer("foo", "bar", "baz", "k", "v"); assertLongTaskTimer(r, c1.id(), 0L, 0, 0L); LongTaskTimer c2 = r.longTaskTimer("foo", ArrayTagSet.create("k", "v").add(new BasicTag("bar", "baz"))); Assertions.assertEquals(c1.id(), c2.id()); long t1 = c1.start(); long t2 = c2.start(); clock.setMonotonicTime(1000L); clock.setWallTime(1L); assertLongTaskTimer(r, c1.id(), 1L, 2, 2.0e-6); c1.stop(t1); assertLongTaskTimer(r, c1.id(), 1L, 1, 1.0e-6); c2.stop(t2); assertLongTaskTimer(r, c1.id(), 1L, 0, 0L); } private void assertGaugeValue(Registry r, Id id, double expected) { PolledMeter.update(r); Assertions.assertEquals(expected, r.gauge(id).value(), 1e-12); } @Test public void testGaugeHelpers() { AtomicLong al1 = new AtomicLong(1L); AtomicLong al2 = new AtomicLong(2L); AtomicLong al4 = new AtomicLong(4L); Registry r = newRegistry(true, 10000); AtomicLong v1 = r.gauge(r.createId("foo", "bar", "baz", "k", "v"), al1); AtomicLong v2 = r.gauge("foo", ArrayTagSet.create("k", "v").add(new BasicTag("bar", "baz")), al2); AtomicLong v3 = r.gauge("foo", al4); Assertions.assertSame(v1, al1); Assertions.assertSame(v2, al2); Assertions.assertSame(v3, al4); Id id1 = r.createId("foo", "bar", "baz", "k", "v"); Id id2 = r.createId("foo"); assertGaugeValue(r, id1, 3.0); assertGaugeValue(r, id2, 4.0); } @Test public void testGaugeHelpersWithFunction() { AtomicLong al1 = new AtomicLong(1L); Registry r = new DefaultRegistry(new ManualClock(40, 0)); DoubleFunction<AtomicLong> f = Functions.age(r.clock()); AtomicLong v1 = r.gauge("foo", al1, f); Assertions.assertSame(v1, al1); Id id1 = r.createId("foo"); assertGaugeValue(r, id1, 39.0 / 1000.0); } @Test public void testGaugeHelpersWithCustomFunction() { AtomicLong al1 = new AtomicLong(1L); Registry r = new DefaultRegistry(new ManualClock(40, 0)); DoubleFunction<AtomicLong> f = new DoubleFunction<AtomicLong>() { @Override public double apply(double v) { return (r.clock().wallTime() - v) / 1000.0; } }; AtomicLong v1 = r.gauge("foo", al1, f); Assertions.assertSame(v1, al1); Id id1 = r.createId("foo"); assertGaugeValue(r, id1, 39.0 / 1000.0); } @Test public void testGaugeHelpersWithCustomFunction2() { AtomicLong al1 = new AtomicLong(1L); Registry r = new DefaultRegistry(new ManualClock(40, 0)); ToDoubleFunction<AtomicLong> f = (obj) -> (r.clock().wallTime() - obj.doubleValue()) / 1000.0; AtomicLong v1 = r.gauge("foo", al1, f); Assertions.assertSame(v1, al1); Id id1 = r.createId("foo"); assertGaugeValue(r, id1, 39.0 / 1000.0); } @Test public void testCollectionSizeHelpers() { Registry r = newRegistry(true, 10000); LinkedBlockingDeque<String> q1 = new LinkedBlockingDeque<>(); LinkedBlockingDeque<String> q2 = r.collectionSize("queueSize", q1); Assertions.assertSame(q1, q2); Id id = r.createId("queueSize"); assertGaugeValue(r, id, 0.0); q2.push("foo"); assertGaugeValue(r, id, 1.0); } @Test public void testMapSizeHelpers() { Registry r = newRegistry(true, 10000); ConcurrentHashMap<String, String> q1 = new ConcurrentHashMap<>(); ConcurrentHashMap<String, String> q2 = r.mapSize("mapSize", q1); Assertions.assertSame(q1, q2); Id id = r.createId("mapSize"); assertGaugeValue(r, id, 0.0); q2.put("foo", "bar"); assertGaugeValue(r, id, 1.0); } @Test public void testMethodValueHelpers() { Registry r = newRegistry(true, 10000); LinkedBlockingDeque<String> q1 = new LinkedBlockingDeque<>(); r.methodValue("queueSize", q1, "size"); Id id = r.createId("queueSize"); assertGaugeValue(r, id, 0.0); q1.push("foo"); assertGaugeValue(r, id, 1.0); } @Test public void methodValueBadReturnType() { Assertions.assertThrows(ClassCastException.class, () -> { Registry r = newRegistry(true, 10000); r.methodValue("queueSize", this, "toString"); }); } @Test public void methodValueBadReturnTypeNoPropagate() { Registry r = newRegistry(false, 10000); r.methodValue("queueSize", this, "toString"); Assertions.assertNull(r.get(r.createId("queueSize"))); } @Test public void methodValueUnknown() { Assertions.assertThrows(RuntimeException.class, () -> { Registry r = newRegistry(true, 10000); r.methodValue("queueSize", this, "unknownMethod"); }); } @Test public void methodValueUnknownNoPropagate() { Registry r = newRegistry(false, 10000); r.methodValue("queueSize", this, "unknownMethod"); Assertions.assertNull(r.get(r.createId("queueSize"))); } @Test public void monitorUsingLambda() { Registry r = newRegistry(true, 10000); GaugeUsingLambda g = new GaugeUsingLambda(r); assertGaugeValue(r, r.createId("test"), 84.0); } public static class GaugeUsingLambda { public GaugeUsingLambda(Registry r) { r.gauge("test", this, (obj) -> obj.getValue()); r.gauge("test", this, GaugeUsingLambda::getValue); } private int getValue() { return 42; } } @Test public void counters() { Registry r = newRegistry(true, 10000); r.counter("foo").increment(); r.counter("foo", "a", "1", "b", "2").increment(); r.counter("foo", "a", "1", "b", "3").increment(13L); r.counter("foo", "a", "1", "b", "2").increment(); r.counter("bar", "a", "1", "b", "2").increment(); Assertions.assertEquals(4, r.counters().count()); final LongSummaryStatistics summary = r.counters() .filter(Functions.nameEquals("foo")) .collect(Collectors.summarizingLong(Counter::count)); Assertions.assertEquals(3L, summary.getCount()); Assertions.assertEquals(16L, summary.getSum()); Assertions.assertEquals(13L, summary.getMax()); } @Test public void timers() { Registry r = newRegistry(true, 10000); r.timer("foo").record(1L, TimeUnit.NANOSECONDS); r.timer("foo", "a", "1", "b", "2").record(1L, TimeUnit.NANOSECONDS); r.timer("foo", "a", "1", "b", "3").record(13L, TimeUnit.NANOSECONDS); r.timer("foo", "a", "1", "b", "2").record(1L, TimeUnit.NANOSECONDS); r.timer("bar", "a", "1", "b", "2").record(1L, TimeUnit.NANOSECONDS); Assertions.assertEquals(4, r.timers().count()); final LongSummaryStatistics countSummary = r.timers() .filter(Functions.nameEquals("foo")) .collect(Collectors.summarizingLong(Timer::count)); Assertions.assertEquals(3L, countSummary.getCount()); Assertions.assertEquals(4L, countSummary.getSum()); Assertions.assertEquals(2L, countSummary.getMax()); final LongSummaryStatistics totalSummary = r.timers() .filter(Functions.nameEquals("foo")) .collect(Collectors.summarizingLong(Timer::totalTime)); Assertions.assertEquals(3L, totalSummary.getCount()); Assertions.assertEquals(16L, totalSummary.getSum()); Assertions.assertEquals(13L, totalSummary.getMax()); } @Test public void distributionSummaries() { Registry r = newRegistry(true, 10000); r.distributionSummary("foo").record(1L); r.distributionSummary("foo", "a", "1", "b", "2").record(1L); r.distributionSummary("foo", "a", "1", "b", "3").record(13L); r.distributionSummary("foo", "a", "1", "b", "2").record(1L); r.distributionSummary("bar", "a", "1", "b", "2").record(1L); Assertions.assertEquals(4, r.distributionSummaries().count()); final LongSummaryStatistics countSummary = r.distributionSummaries() .filter(Functions.nameEquals("foo")) .collect(Collectors.summarizingLong(DistributionSummary::count)); Assertions.assertEquals(3L, countSummary.getCount()); Assertions.assertEquals(4L, countSummary.getSum()); Assertions.assertEquals(2L, countSummary.getMax()); final LongSummaryStatistics totalSummary = r.distributionSummaries() .filter(Functions.nameEquals("foo")) .collect(Collectors.summarizingLong(DistributionSummary::totalAmount)); Assertions.assertEquals(3L, totalSummary.getCount()); Assertions.assertEquals(16L, totalSummary.getSum()); Assertions.assertEquals(13L, totalSummary.getMax()); } @Test public void gauges() { Registry r = newRegistry(true, 10000); r.gauge(r.createId("foo", "a", "1")).set(1.0); r.gauge(r.createId("foo", "a", "2")).set(2.0); r.gauge(r.createId("bar")).set(7.0); Assertions.assertEquals(3, r.gauges().count()); final DoubleSummaryStatistics valueSummary = r.gauges() .filter(Functions.nameEquals("foo")) .collect(Collectors.summarizingDouble(Gauge::value)); Assertions.assertEquals(2, valueSummary.getCount()); Assertions.assertEquals(3.0, valueSummary.getSum(), 1e-12); Assertions.assertEquals(1.5, valueSummary.getAverage(), 1e-12); } @Test public void maxGauge() { Registry r = newRegistry(true, 10000); r.maxGauge("foo").set(1.0); r.maxGauge("foo").set(3.0); r.maxGauge("foo").set(2.0); final DoubleSummaryStatistics valueSummary = r.gauges() .filter(Functions.nameEquals("foo")) .collect(Collectors.summarizingDouble(Gauge::value)); Assertions.assertEquals(1, valueSummary.getCount()); Assertions.assertEquals(3.0, valueSummary.getSum(), 1e-12); } @Test public void propagateWarningsDefault() { RegistryConfig config = k -> null; Registry r = new DefaultRegistry(Clock.SYSTEM, config); r.propagate("foo", new RuntimeException("test")); } @Test public void propagateWarningsFalse() { RegistryConfig config = k -> "propagateWarnings".equals(k) ? "false" : null; Registry r = new DefaultRegistry(Clock.SYSTEM, config); r.propagate("foo", new RuntimeException("test")); } @Test public void propagateWarningsTrue() { Assertions.assertThrows(RuntimeException.class, () -> { RegistryConfig config = k -> "propagateWarnings".equals(k) ? "true" : null; Registry r = new DefaultRegistry(Clock.SYSTEM, config); r.propagate("foo", new RuntimeException("test")); }); } @Test public void keepNonExpired() { ManualClock clock = new ManualClock(); ExpiringRegistry registry = new ExpiringRegistry(clock); registry.counter("test").increment(); registry.removeExpiredMeters(); Assertions.assertEquals(1, registry.counters().count()); } @Test public void removeExpired() { ManualClock clock = new ManualClock(); ExpiringRegistry registry = new ExpiringRegistry(clock); registry.counter("test").increment(); clock.setWallTime(1); registry.removeExpiredMeters(); Assertions.assertEquals(0, registry.counters().count()); } @Test public void resurrectExpiredUsingComposite() { ManualClock clock = new ManualClock(); ExpiringRegistry registry = new ExpiringRegistry(clock); CompositeRegistry cr = Spectator.globalRegistry(); cr.removeAll(); cr.add(registry); cr.counter("test").increment(); clock.setWallTime(60000 * 30); registry.removeExpiredMeters(); Assertions.assertEquals(0, registry.counters().count()); cr.counter("test").increment(); Assertions.assertEquals(1, registry.counters().count()); } @Test public void resurrectUsingCachedRef() { ManualClock clock = new ManualClock(); ExpiringRegistry registry = new ExpiringRegistry(clock); Counter c = registry.counter("test"); c.increment(); clock.setWallTime(60000 * 30); registry.removeExpiredMeters(); Assertions.assertEquals(0, registry.counters().count()); c.increment(); Assertions.assertEquals(1, registry.counters().count()); } @Test public void resurrectUsingCachedRefInit() { ManualClock clock = new ManualClock(); ExpiringRegistry registry = new ExpiringRegistry(clock); Counter c = registry.counter("test"); clock.setWallTime(60000 * 30); registry.removeExpiredMeters(); Assertions.assertEquals(0, registry.counters().count()); c.increment(); Assertions.assertEquals(1, registry.counters().count()); } @Test public void resurrectUsingCachedRefInitTimer() { ManualClock clock = new ManualClock(); ExpiringRegistry registry = new ExpiringRegistry(clock); Timer t = registry.timer("test"); clock.setWallTime(60000 * 30); registry.removeExpiredMeters(); Assertions.assertEquals(0, registry.timers().count()); t.record(42, TimeUnit.NANOSECONDS); Assertions.assertEquals(1, registry.timers().count()); } @Test public void resurrectExpiredUsingCompositeCachedRef() { ManualClock clock = new ManualClock(); ExpiringRegistry registry = new ExpiringRegistry(clock); CompositeRegistry cr = Spectator.globalRegistry(); cr.removeAll(); cr.add(registry); Counter c = cr.counter("test"); c.increment(); clock.setWallTime(60000 * 30); registry.removeExpiredMeters(); Assertions.assertEquals(0, registry.counters().count()); c.increment(); Assertions.assertEquals(1, registry.counters().count()); } @Test public void resurrectUsingLambda() { ManualClock clock = new ManualClock(); ExpiringRegistry registry = new ExpiringRegistry(clock); Timer t = registry.timer("test"); t.record(() -> { // Force expiration in the body of the lambda clock.setWallTime(60000 * 30); registry.removeExpiredMeters(); Assertions.assertEquals(0, registry.timers().count()); }); Assertions.assertEquals(1, registry.timers().count()); } @Test public void expireAndResurrectLoop() { ManualClock clock = new ManualClock(); ExpiringRegistry registry = new ExpiringRegistry(clock); Counter c = registry.counter("test"); for (int i = 0; i < 1000; ++i) { clock.setWallTime(60000 * 30 * i); registry.removeExpiredMeters(); c.increment(); Assertions.assertEquals(1, c.count()); Assertions.assertEquals(1, registry.counter("test").count()); } } @Test public void uncaughtExceptionFromGaugeFunction() { Assertions.assertThrows(RuntimeException.class, () -> { Registry registry = new DefaultRegistry(); PolledMeter.using(registry) .withName("test") .monitorValue(new RuntimeException("failure"), value -> { throw value; }); PolledMeter.update(registry); }); } @Test public void defaultResetRemovesMeters() { DefaultRegistry r = newRegistry(true, 10000); r.counter("test").increment(); Assertions.assertEquals(1, r.stream().count()); r.reset(); Assertions.assertEquals(0, r.stream().count()); } @Test public void defaultResetRemovesState() { DefaultRegistry r = newRegistry(true, 10000); AtomicInteger v = new AtomicInteger(); PolledMeter.using(r).withName("test").monitorValue(v); PolledMeter.update(r); Assertions.assertEquals(1, r.stream().count()); Assertions.assertEquals(1, r.state().size()); r.reset(); PolledMeter.update(r); Assertions.assertEquals(0, r.stream().count()); Assertions.assertEquals(0, r.state().size()); } @Test public void maxGaugeCanBeNegative() { DefaultRegistry r = newRegistry(false, 10); r.maxGauge("test").set(-42); Assertions.assertEquals(-42.0, r.maxGauge("test").value(), 1e-12); } @Test public void spliteratorCharacteristicsAndEstimatedSize() { Registry registry = newRegistry(false, 20); registry.counter("foo").increment(); registry.counter("bar").increment(); registry.counter("baz").increment(); Spliterator<Meter> spliterator = registry.spliterator(); Assertions.assertTrue(spliterator.hasCharacteristics(Spliterator.NONNULL)); Assertions.assertTrue(spliterator.hasCharacteristics(Spliterator.CONCURRENT)); Assertions.assertEquals(3, spliterator.estimateSize()); } @Test public void customIdTags() { DefaultRegistry r = newRegistry(false, 10000); Id id = new CustomId("test").withTags("b", "2", "a", "1"); r.counter(id).increment(); Assertions.assertEquals(1, r.counter("test", "a", "1", "b", "2").count()); } @Test public void customIdCounter() { DefaultRegistry r = newRegistry(false, 10000); Id id = new CustomId("test"); r.counter(id).increment(); Assertions.assertEquals(1, r.counter("test").count()); } @Test public void customIdGauge() { DefaultRegistry r = newRegistry(false, 10000); Id id = new CustomId("test"); r.gauge(id).set(42.0); Assertions.assertEquals(42.0, r.gauge("test").value(), 1e-12); } @Test public void customIdMaxGauge() { DefaultRegistry r = newRegistry(false, 10000); Id id = new CustomId("test"); r.maxGauge(id).set(42.0); Assertions.assertEquals(42.0, r.maxGauge("test").value(), 1e-12); } @Test public void customIdTimer() { DefaultRegistry r = newRegistry(false, 10000); Id id = new CustomId("test"); r.timer(id).record(42, TimeUnit.NANOSECONDS); Assertions.assertEquals(42L, r.timer("test").totalTime()); } @Test public void customIdDistributionSummary() { DefaultRegistry r = newRegistry(false, 10000); Id id = new CustomId("test"); r.distributionSummary(id).record(42); Assertions.assertEquals(42L, r.distributionSummary("test").totalAmount()); } @Test public void customIdGetKey() { Id id = new CustomId("test").withTags("b", "2", "a", "1"); Assertions.assertEquals("name", id.getKey(0)); Assertions.assertEquals("b", id.getKey(1)); Assertions.assertEquals("a", id.getKey(2)); } @Test public void customIdGetValue() { Id id = new CustomId("test").withTags("b", "2", "a", "1"); Assertions.assertEquals("test", id.getValue(0)); Assertions.assertEquals("2", id.getValue(1)); Assertions.assertEquals("1", id.getValue(2)); } @Test public void customIdSize() { Id id = new CustomId("test").withTags("b", "2", "a", "1"); Assertions.assertEquals(3, id.size()); } // Used to test that custom Id implementations will get normalized correctly and that // backwards compatibility for inheritance is maintained. public static class CustomId implements Id { private final String name; private final List<Tag> tags; CustomId(String name) { this(name, Collections.emptyList()); } CustomId(String name, List<Tag> tags) { this.name = name; this.tags = Collections.unmodifiableList(tags); } private List<Tag> append(Tag tag) { List<Tag> tmp = new ArrayList<>(tags); tmp.add(tag); return tmp; } @Override public String name() { return name; } @Override public Iterable<Tag> tags() { return tags; } @Override public Id withTag(String k, String v) { return new CustomId(name, append(Tag.of(k, v))); } @Override public Id withTag(Tag t) { return new CustomId(name, append(t)); } } }
5,703
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/RegistryExceptionsTest.java
/* * Copyright 2014-2021 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import org.junit.jupiter.api.Test; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * Uses reflection to call all public methods of Registry with various values including * {@code null} to try and ensure that exceptions are not propagated unless that is explicitly * enabled. */ public class RegistryExceptionsTest { private static final Object[] FALLBACK = new Object[] {null}; private static final Map<Class<?>, Object[]> SAMPLE_VALUES = new HashMap<>(); static { SAMPLE_VALUES.put( String.class, new Object[] {"foo", "", null} ); SAMPLE_VALUES.put( String[].class, new Object[] { new String[] {"a", "1", "b", "2"}, new String[] {"a", "1", "b"}, new String[] {"a", "1", "b", null}, new String[] {"a", "1", null, "2"}, null } ); SAMPLE_VALUES.put( Iterable.class, new Object[] { Arrays.asList("a", "1", "b", "2"), Arrays.asList("a", "1", "b"), null } ); SAMPLE_VALUES.put( Id.class, new Object[] { Id.create("foo"), Id.create(""), null } ); } @Test public void exceptionsNotPropagated() throws Exception { Method[] methods = DefaultRegistry.class.getMethods(); for (Method method : methods) { if (Registry.class.isAssignableFrom(method.getDeclaringClass())) { invokeWithSampleValues(method); } } } private void invokeWithSampleValues(Method method) throws Exception { Object[] params = new Object[method.getParameterCount()]; Class<?>[] ptypes = method.getParameterTypes(); invoke(method, params, ptypes, 0); } private void invoke(Method method, Object[] params, Class<?>[] ptypes, int i) throws Exception { if (i == params.length) { method.invoke(new DefaultRegistry(Clock.SYSTEM, p -> null), params); } else { Object[] values = SAMPLE_VALUES.getOrDefault(ptypes[i], FALLBACK); for (Object value : values) { params[i] = value; invoke(method, params, ptypes, i + 1); } } } }
5,704
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/NoopTimerTest.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; public class NoopTimerTest { @Test public void testId() { Assertions.assertEquals(NoopTimer.INSTANCE.id(), NoopId.INSTANCE); Assertions.assertFalse(NoopTimer.INSTANCE.hasExpired()); } @Test public void testRecord() { NoopTimer t = NoopTimer.INSTANCE; t.record(42, TimeUnit.MILLISECONDS); Assertions.assertEquals(t.count(), 0L); Assertions.assertEquals(t.totalTime(), 0L); } @Test public void testRecordCallableException() throws Exception { NoopTimer t = NoopTimer.INSTANCE; boolean seen = false; try { t.record(() -> { throw new Exception("foo"); }); } catch (Exception e) { seen = true; } Assertions.assertTrue(seen); } @Test public void testRecordRunnable() throws Exception { NoopTimer t = NoopTimer.INSTANCE; AtomicBoolean run = new AtomicBoolean(); t.record(() -> run.set(true)); Assertions.assertTrue(run.get()); } @Test public void testMeasure() { NoopTimer t = NoopTimer.INSTANCE; t.record(42, TimeUnit.MILLISECONDS); Assertions.assertFalse(t.measure().iterator().hasNext()); } }
5,705
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/UtilsTest.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; public class UtilsTest { private List<Measurement> newList(int size) { Registry r = new DefaultRegistry(); List<Measurement> data = new ArrayList<>(); for (int i = 0; i < size; ++i) { data.add(new Measurement(r.createId("foo", "i", "" + i), 0L, i)); } return data; } @Test public void getTagValueIdNoTags() { Registry r = new DefaultRegistry(); Id id = r.createId("foo"); Assertions.assertNull(Utils.getTagValue(id, "abc")); } @Test public void getTagValueId() { Registry r = new DefaultRegistry(); Id id = r.createId("foo", "bar", "baz", "abc", "def"); Assertions.assertEquals("def", Utils.getTagValue(id, "abc")); Assertions.assertEquals("baz", Utils.getTagValue(id, "bar")); } @Test public void getTagValueIterable() { Registry r = new DefaultRegistry(); Id id = r.createId("foo", "bar", "baz", "abc", "def"); Assertions.assertEquals("def", Utils.getTagValue(id.tags()::iterator, "abc")); } @Test public void firstTag() { List<Measurement> ms = newList(10); Tag t = new BasicTag("i", "7"); Measurement m = Utils.first(ms, t); Assertions.assertEquals(m.id().tags(), ArrayTagSet.create(t)); } @Test public void firstKV() { List<Measurement> ms = newList(10); Tag t = new BasicTag("i", "7"); Measurement m = Utils.first(ms, "i", "7"); Assertions.assertEquals(m.id().tags(), ArrayTagSet.create(t)); } @Test public void firstPredicate() { List<Measurement> ms = newList(10); Tag t = new BasicTag("i", "7"); Measurement m = Utils.first(ms, v -> v.value() == 7.0); Assertions.assertEquals(m.id().tags(), ArrayTagSet.create(t)); } @Test public void firstPredicateEmpty() { List<Measurement> ms = newList(10); Measurement m = Utils.first(ms, v -> false); Assertions.assertNull(m); } @Test public void filterTag() { List<Measurement> ms = newList(10); Tag t = new BasicTag("i", "7"); List<Measurement> out = Utils.toList(Utils.filter(ms, t)); Assertions.assertEquals(1, out.size()); Assertions.assertEquals(out.get(0).id().tags(), ArrayTagSet.create(t)); } @Test public void filterKV() { List<Measurement> ms = newList(10); Tag t = new BasicTag("i", "7"); List<Measurement> out = Utils.toList(Utils.filter(ms, "i", "7")); Assertions.assertEquals(1, out.size()); Assertions.assertEquals(out.get(0).id().tags(), ArrayTagSet.create(t)); } @Test public void filterPredicate() { List<Measurement> ms = newList(10); Tag t = new BasicTag("i", "7"); List<Measurement> out = Utils.toList(Utils.filter(ms, v -> v.value() == 7.0)); Assertions.assertEquals(1, out.size()); Assertions.assertEquals(out.get(0).id().tags(), ArrayTagSet.create(t)); } @Test public void filterPredicateEmpty() { List<Measurement> ms = newList(10); List<Measurement> out = Utils.toList(Utils.filter(ms, v -> false)); Assertions.assertEquals(0, out.size()); } @Test public void sizeTagList() { Id id = Id.create("test").withTags("a", "1", "b", "2"); Assertions.assertEquals(2, Utils.size(id.tags())); } @Test public void sizeCollection() { List<String> vs = new ArrayList<>(); vs.add("a"); vs.add("b"); vs.add("c"); Assertions.assertEquals(3, Utils.size(vs)); } @Test public void sizeIterable() { List<String> vs = new ArrayList<>(); vs.add("a"); vs.add("b"); Assertions.assertEquals(2, Utils.size(vs::iterator)); } @Test public void getValueList() { List<String> vs = new ArrayList<>(); vs.add("a"); vs.add("b"); vs.add("c"); Assertions.assertEquals("a", Utils.getValue(vs, 0)); Assertions.assertEquals("b", Utils.getValue(vs, 1)); Assertions.assertEquals("c", Utils.getValue(vs, 2)); Assertions.assertThrows(IndexOutOfBoundsException.class, () -> Utils.getValue(vs, 3)); Assertions.assertThrows(IndexOutOfBoundsException.class, () -> Utils.getValue(vs, -3)); } @Test public void getValueIterable() { List<String> vs = new ArrayList<>(); vs.add("a"); vs.add("b"); vs.add("c"); Iterable<String> it = vs::iterator; Assertions.assertEquals("a", Utils.getValue(it, 0)); Assertions.assertEquals("b", Utils.getValue(it, 1)); Assertions.assertEquals("c", Utils.getValue(it, 2)); Assertions.assertThrows(IndexOutOfBoundsException.class, () -> Utils.getValue(it, 3)); Assertions.assertThrows(IndexOutOfBoundsException.class, () -> Utils.getValue(it, -3)); } }
5,706
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/SwapMeterTest.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.function.LongSupplier; public class SwapMeterTest { private static final LongSupplier VERSION = () -> 0L; private final ManualClock clock = new ManualClock(); private final Registry registry = new DefaultRegistry(); private final Id counterId = registry.createId("counter"); private final Id gaugeId = registry.createId("gauge"); private final Id timerId = registry.createId("timer"); private final Id distSummaryId = registry.createId("distSummary"); @Test public void wrappedCounters() { Counter c = new DefaultCounter(clock, counterId); SwapCounter sc1 = new SwapCounter(registry, VERSION, counterId, c); SwapCounter sc2 = new SwapCounter(registry, VERSION, counterId, sc1); Assertions.assertFalse(sc2.hasExpired()); sc2.increment(); Assertions.assertEquals(1, c.count()); Assertions.assertEquals(1, sc1.count()); Assertions.assertEquals(1, sc2.count()); } @Test public void wrapExpiredCounter() { ExpiringRegistry registry = new ExpiringRegistry(clock); Counter c = registry.counter(counterId); clock.setWallTime(60000 * 30); SwapCounter s1 = new SwapCounter(registry, VERSION, counterId, c); s1.increment(); Assertions.assertEquals(1, c.count()); Assertions.assertEquals(1, s1.count()); } @Test public void wrappedCounterBatchUpdater() throws Exception { Counter c = new DefaultCounter(clock, counterId); SwapCounter sc = new SwapCounter(registry, VERSION, counterId, c); try (Counter.BatchUpdater b = sc.batchUpdater(2)) { b.increment(); } Assertions.assertEquals(1, c.count()); Assertions.assertEquals(1, sc.count()); } @Test public void wrappedCounterBatchUpdaterCustom() throws Exception { ExpiringRegistry registry = new ExpiringRegistry(clock); Counter c = registry.counter(counterId); try (Counter.BatchUpdater b = c.batchUpdater(2)) { b.increment(); } Assertions.assertEquals(1, c.count()); } @Test public void wrappedTimerBatchUpdater() throws Exception { Timer t = new DefaultTimer(clock, timerId); SwapTimer st = new SwapTimer(registry, VERSION, timerId, t); try (Timer.BatchUpdater b = st.batchUpdater(2)) { b.record(1, TimeUnit.NANOSECONDS); } Assertions.assertEquals(1, t.count()); Assertions.assertEquals(1, st.count()); } @Test public void wrappedTimerBatchUpdaterCustom() throws Exception { ExpiringRegistry registry = new ExpiringRegistry(clock); Timer t = registry.timer(timerId); try (Timer.BatchUpdater b = t.batchUpdater(2)) { b.record(1, TimeUnit.NANOSECONDS); } Assertions.assertEquals(1, t.count()); } @Test public void wrappedDistributionSummaryBatchUpdater() throws Exception { DistributionSummary d = new DefaultDistributionSummary(clock, distSummaryId); SwapDistributionSummary sd = new SwapDistributionSummary(registry, VERSION, distSummaryId, d); try (DistributionSummary.BatchUpdater b = sd.batchUpdater(2)) { b.record(1); } Assertions.assertEquals(1, d.count()); Assertions.assertEquals(1, sd.count()); } @Test public void wrappedDistributionSummaryBatchUpdaterCustom() throws Exception { ExpiringRegistry registry = new ExpiringRegistry(clock); DistributionSummary d = registry.distributionSummary(distSummaryId); try (DistributionSummary.BatchUpdater b = d.batchUpdater(2)) { b.record(1); } Assertions.assertEquals(1, d.count()); } @Test public void wrapExpiredTimer() { ExpiringRegistry registry = new ExpiringRegistry(clock); Timer t = registry.timer(timerId); clock.setWallTime(60000 * 30); SwapTimer s1 = new SwapTimer(registry, VERSION, timerId, t); s1.record(42, TimeUnit.NANOSECONDS); Assertions.assertEquals(1, t.count()); Assertions.assertEquals(1, s1.count()); } @Test public void wrapExpiredGauge() { ExpiringRegistry registry = new ExpiringRegistry(clock); Gauge c = registry.gauge(gaugeId); clock.setWallTime(60000 * 30); SwapGauge s1 = new SwapGauge(registry, VERSION, gaugeId, c); s1.set(1.0); Assertions.assertEquals(1.0, c.value(), 1e-12); Assertions.assertEquals(1.0, s1.value(), 1e-12); } @Test public void wrapExpiredDistSummary() { ExpiringRegistry registry = new ExpiringRegistry(clock); DistributionSummary c = registry.distributionSummary(distSummaryId); clock.setWallTime(60000 * 30); SwapDistributionSummary s1 = new SwapDistributionSummary(registry, VERSION, distSummaryId, c); s1.record(1); Assertions.assertEquals(1, c.count()); Assertions.assertEquals(1, s1.count()); } @Test public void versionUpdateExpiration() { AtomicLong version = new AtomicLong(); Counter c = new DefaultCounter(clock, counterId); SwapCounter sc = new SwapCounter(registry, version::get, counterId, c); sc.increment(); Assertions.assertFalse(sc.hasExpired()); version.incrementAndGet(); Assertions.assertTrue(sc.hasExpired()); sc.increment(); Assertions.assertFalse(sc.hasExpired()); } }
5,707
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/ExpiringRegistry.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import java.util.Collections; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Supplier; public class ExpiringRegistry extends AbstractRegistry { public ExpiringRegistry(Clock clock) { super(clock); } @Override protected Counter newCounter(Id id) { return new Counter() { private final long creationTime = clock().wallTime(); private double count = 0; @Override public void add(double amount) { count += amount; } @Override public double actualCount() { return count; } @Override public Id id() { return id; } @Override public Iterable<Measurement> measure() { return Collections.emptyList(); } @Override public boolean hasExpired() { return clock().wallTime() > creationTime; } @Override public BatchUpdater batchUpdater(int batchSize) { return new CounterUpdater(); } }; } private static class CounterUpdater implements Counter.BatchUpdater, Consumer<Supplier<Counter>> { private Supplier<Counter> counterSupplier; private double sum; @Override public void add(double amount) { sum += amount; } @Override public void flush() { counterSupplier.get().add(sum); sum = 0.0; } @Override public void close() throws Exception { flush(); } @Override public void accept(Supplier<Counter> counterSupplier) { this.counterSupplier = counterSupplier; } } @Override protected DistributionSummary newDistributionSummary(Id id) { return new DistributionSummary() { private final long creationTime = clock().wallTime(); private long count = 0; @Override public void record(long amount) { ++count; } @Override public long count() { return count; } @Override public long totalAmount() { return 0; } @Override public Id id() { return id; } @Override public Iterable<Measurement> measure() { return Collections.emptyList(); } @Override public boolean hasExpired() { return clock().wallTime() > creationTime; } @Override public BatchUpdater batchUpdater(int batchSize) { return new DistributionSummaryUpdater(); } }; } private static class DistributionSummaryUpdater implements DistributionSummary.BatchUpdater, Consumer<Supplier<DistributionSummary>> { private Supplier<DistributionSummary> distSummarySupplier; @Override public void record(long amount) { distSummarySupplier.get().record(amount); } @Override public void flush() { } @Override public void close() throws Exception { } @Override public void accept(Supplier<DistributionSummary> distSummarySupplier) { this.distSummarySupplier = distSummarySupplier; } } @Override protected Timer newTimer(Id id) { return new AbstractTimer(clock()) { private final long creationTime = clock().wallTime(); private long count = 0; @Override public void record(long amount, TimeUnit unit) { ++count; } @Override public long count() { return count; } @Override public long totalTime() { return 0; } @Override public Id id() { return id; } @Override public Iterable<Measurement> measure() { return Collections.emptyList(); } @Override public boolean hasExpired() { return clock().wallTime() > creationTime; } @Override public BatchUpdater batchUpdater(int batchSize) { return new TimerUpdater(); } }; } private static class TimerUpdater implements Timer.BatchUpdater, Consumer<Supplier<Timer>> { private Supplier<Timer> timerSupplier; @Override public void record(long amount, TimeUnit unit) { timerSupplier.get().record(amount, unit); } @Override public void flush() { } @Override public void close() throws Exception { } @Override public void accept(Supplier<Timer> timerSupplier) { this.timerSupplier = timerSupplier; } } @Override protected Gauge newGauge(Id id) { return new Gauge() { private final long creationTime = clock().wallTime(); private double value = 0.0; @Override public void set(double v) { value = v; } @Override public double value() { return value; } @Override public Id id() { return id; } @Override public Iterable<Measurement> measure() { return Collections.emptyList(); } @Override public boolean hasExpired() { return clock().wallTime() > creationTime; } }; } @Override protected Gauge newMaxGauge(Id id) { return newGauge(id); } @Override public void removeExpiredMeters() { super.removeExpiredMeters(); } }
5,708
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/TestRegistryConfig.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; class TestRegistryConfig implements RegistryConfig { private final boolean warnings; private final int numberOfMeters; TestRegistryConfig(boolean warnings, int numberOfMeters) { this.warnings = warnings; this.numberOfMeters = numberOfMeters; } @Override public String get(String k) { switch (k) { case "propagateWarnings": return Boolean.toString(warnings); case "maxNumberOfMeters": return Integer.toString(numberOfMeters); default: return null; } } }
5,709
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/DefaultCounterTest.java
/* * Copyright 2014-2022 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class DefaultCounterTest { private final ManualClock clock = new ManualClock(); @Test public void testInit() { Counter c = new DefaultCounter(clock, NoopId.INSTANCE); Assertions.assertEquals(c.count(), 0L); } @Test public void testIncrement() { Counter c = new DefaultCounter(clock, NoopId.INSTANCE); c.increment(); Assertions.assertEquals(c.count(), 1L); c.increment(); c.increment(); Assertions.assertEquals(c.count(), 3L); } @Test public void testIncrementBatch() throws Exception { Counter c = new DefaultCounter(clock, NoopId.INSTANCE); try (Counter.BatchUpdater b = c.batchUpdater(2)) { b.increment(); Assertions.assertEquals(c.count(), 0L); b.increment(); Assertions.assertEquals(c.count(), 2L); b.increment(); Assertions.assertEquals(c.count(), 2L); } Assertions.assertEquals(c.count(), 3L); } @Test public void testIncrementAmount() { Counter c = new DefaultCounter(clock, NoopId.INSTANCE); c.increment(42); Assertions.assertEquals(c.count(), 42L); } @Test public void testIncrementAmountBatch() throws Exception { Counter c = new DefaultCounter(clock, NoopId.INSTANCE); try (Counter.BatchUpdater b = c.batchUpdater(2)) { b.increment(42); } Assertions.assertEquals(c.count(), 42L); } @Test public void testAddAmount() { Counter c = new DefaultCounter(clock, NoopId.INSTANCE); c.add(42.0); Assertions.assertEquals(c.actualCount(), 42.0, 1e-12); } @Test public void testAddAmountBatch() throws Exception { Counter c = new DefaultCounter(clock, NoopId.INSTANCE); try (Counter.BatchUpdater b = c.batchUpdater(2)) { b.add(42.0); } Assertions.assertEquals(c.actualCount(), 42.0, 1e-12); } @Test public void testAddNegativeAmount() { Counter c = new DefaultCounter(clock, NoopId.INSTANCE); c.add(-42.0); Assertions.assertEquals(c.actualCount(), 0.0, 1e-12); } @Test public void testAddNegativeAmountBatch() throws Exception { Counter c = new DefaultCounter(clock, NoopId.INSTANCE); try (Counter.BatchUpdater b = c.batchUpdater(2)) { b.add(-42.0); } Assertions.assertEquals(c.actualCount(), 0.0, 1e-12); } @Test public void testAddNaN() { Counter c = new DefaultCounter(clock, NoopId.INSTANCE); c.add(1.0); c.add(Double.NaN); Assertions.assertEquals(c.actualCount(), 1.0, 1e-12); } @Test public void testAddNaNBatch() throws Exception { Counter c = new DefaultCounter(clock, NoopId.INSTANCE); try (Counter.BatchUpdater b = c.batchUpdater(2)) { b.add(1.0); b.add(Double.NaN); } Assertions.assertEquals(c.actualCount(), 1.0, 1e-12); } @Test public void testAddInfinity() { Counter c = new DefaultCounter(clock, NoopId.INSTANCE); c.add(Double.POSITIVE_INFINITY); Assertions.assertEquals(c.actualCount(), 0.0, 1e-12); } @Test public void testAddInfinityBatch() throws Exception { Counter c = new DefaultCounter(clock, NoopId.INSTANCE); try (Counter.BatchUpdater b = c.batchUpdater(2)) { b.add(Double.POSITIVE_INFINITY); } Assertions.assertEquals(c.actualCount(), 0.0, 1e-12); } @Test public void testMeasure() { Counter c = new DefaultCounter(clock, NoopId.INSTANCE); c.increment(42); clock.setWallTime(3712345L); for (Measurement m : c.measure()) { Assertions.assertEquals(m.id(), c.id()); Assertions.assertEquals(m.timestamp(), 3712345L); Assertions.assertEquals(m.value(), 42.0, 0.1e-12); } } }
5,710
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/NoopCounterTest.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class NoopCounterTest { @Test public void testId() { Assertions.assertEquals(NoopCounter.INSTANCE.id(), NoopId.INSTANCE); Assertions.assertFalse(NoopCounter.INSTANCE.hasExpired()); } @Test public void testIncrement() { NoopCounter c = NoopCounter.INSTANCE; c.increment(); Assertions.assertEquals(c.count(), 0L); } @Test public void testIncrementAmount() { NoopCounter c = NoopCounter.INSTANCE; c.increment(42); Assertions.assertEquals(c.count(), 0L); } @Test public void testMeasure() { NoopCounter c = NoopCounter.INSTANCE; c.increment(42); Assertions.assertFalse(c.measure().iterator().hasNext()); } }
5,711
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/DefaultTimerTest.java
/* * Copyright 2014-2022 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.lang.reflect.Proxy; import java.time.Duration; import java.util.Arrays; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.BinaryOperator; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import java.util.function.DoubleBinaryOperator; import java.util.function.DoubleConsumer; import java.util.function.DoublePredicate; import java.util.function.DoubleSupplier; import java.util.function.DoubleToIntFunction; import java.util.function.DoubleToLongFunction; import java.util.function.DoubleUnaryOperator; import java.util.function.Function; import java.util.function.IntBinaryOperator; import java.util.function.IntConsumer; import java.util.function.IntFunction; import java.util.function.IntPredicate; import java.util.function.IntSupplier; import java.util.function.IntToDoubleFunction; import java.util.function.IntToLongFunction; import java.util.function.IntUnaryOperator; import java.util.function.LongBinaryOperator; import java.util.function.LongConsumer; import java.util.function.LongFunction; import java.util.function.LongPredicate; import java.util.function.LongSupplier; import java.util.function.LongToDoubleFunction; import java.util.function.LongToIntFunction; import java.util.function.LongUnaryOperator; import java.util.function.ObjDoubleConsumer; import java.util.function.ObjIntConsumer; import java.util.function.ObjLongConsumer; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.function.ToDoubleBiFunction; import java.util.function.ToDoubleFunction; import java.util.function.ToIntBiFunction; import java.util.function.ToIntFunction; import java.util.function.ToLongBiFunction; import java.util.function.ToLongFunction; import java.util.function.UnaryOperator; public class DefaultTimerTest { private final ManualClock clock = new ManualClock(); @Test public void testInit() { Timer t = new DefaultTimer(clock, NoopId.INSTANCE); Assertions.assertEquals(t.count(), 0L); Assertions.assertEquals(t.totalTime(), 0L); Assertions.assertFalse(t.hasExpired()); } @Test public void testRecord() { Timer t = new DefaultTimer(clock, NoopId.INSTANCE); t.record(42, TimeUnit.MILLISECONDS); Assertions.assertEquals(t.count(), 1L); Assertions.assertEquals(t.totalTime(), 42000000L); } @Test public void testRecordBatch() throws Exception { Timer t = new DefaultTimer(clock, NoopId.INSTANCE); try (Timer.BatchUpdater b = t.batchUpdater(2)) { b.record(42, TimeUnit.MILLISECONDS); b.record(42, TimeUnit.MILLISECONDS); Assertions.assertEquals(t.count(), 2L); Assertions.assertEquals(t.totalTime(), 84000000L); b.record(1, TimeUnit.MILLISECONDS); } Assertions.assertEquals(t.count(), 3L); Assertions.assertEquals(t.totalTime(), 85000000L); } @Test public void testRecordDuration() { Timer t = new DefaultTimer(clock, NoopId.INSTANCE); t.record(Duration.ofMillis(42)); Assertions.assertEquals(t.count(), 1L); Assertions.assertEquals(t.totalTime(), 42000000L); } @Test public void testRecordDurationBatch() throws Exception { Timer t = new DefaultTimer(clock, NoopId.INSTANCE); try (Timer.BatchUpdater b = t.batchUpdater(2)) { b.record(Duration.ofMillis(42)); } Assertions.assertEquals(t.count(), 1L); Assertions.assertEquals(t.totalTime(), 42000000L); } @Test public void testRecordNegative() { Timer t = new DefaultTimer(clock, NoopId.INSTANCE); t.record(-42, TimeUnit.MILLISECONDS); Assertions.assertEquals(t.count(), 0L); Assertions.assertEquals(t.totalTime(), 0L); } @Test public void testRecordNegativeBatch() throws Exception { Timer t = new DefaultTimer(clock, NoopId.INSTANCE); try (Timer.BatchUpdater b = t.batchUpdater(2)) { b.record(-42, TimeUnit.MILLISECONDS); } Assertions.assertEquals(t.count(), 0L); Assertions.assertEquals(t.totalTime(), 0L); } @Test public void testRecordZero() { Timer t = new DefaultTimer(clock, NoopId.INSTANCE); t.record(0, TimeUnit.MILLISECONDS); Assertions.assertEquals(t.count(), 1L); Assertions.assertEquals(t.totalTime(), 0L); } @Test public void testRecordZeroBatch() throws Exception { Timer t = new DefaultTimer(clock, NoopId.INSTANCE); try (Timer.BatchUpdater b = t.batchUpdater(2)) { b.record(0, TimeUnit.MILLISECONDS); } Assertions.assertEquals(t.count(), 1L); Assertions.assertEquals(t.totalTime(), 0L); } @Test public void testRecordCallable() throws Exception { Timer t = new DefaultTimer(clock, NoopId.INSTANCE); clock.setMonotonicTime(100L); int v = t.recordCallable(() -> { clock.setMonotonicTime(500L); return 42; }); Assertions.assertEquals(v, 42); Assertions.assertEquals(t.count(), 1L); Assertions.assertEquals(t.totalTime(), 400L); } @Test public void testRecordCallableException() throws Exception { Timer t = new DefaultTimer(clock, NoopId.INSTANCE); clock.setMonotonicTime(100L); boolean seen = false; try { t.recordCallable(() -> { clock.setMonotonicTime(500L); throw new Exception("foo"); }); } catch (Exception e) { seen = true; } Assertions.assertTrue(seen); Assertions.assertEquals(t.count(), 1L); Assertions.assertEquals(t.totalTime(), 400L); } @Test public void testRecordRunnable() throws Exception { Timer t = new DefaultTimer(clock, NoopId.INSTANCE); clock.setMonotonicTime(100L); t.recordRunnable(() -> clock.setMonotonicTime(500L)); Assertions.assertEquals(t.count(), 1L); Assertions.assertEquals(t.totalTime(), 400L); } @Test public void testRecordRunnableException() { Timer t = new DefaultTimer(clock, NoopId.INSTANCE); clock.setMonotonicTime(100L); boolean seen = false; try { t.recordRunnable(() -> { clock.setMonotonicTime(500L); throw new RuntimeException("foo"); }); } catch (Exception e) { seen = true; } Assertions.assertTrue(seen); Assertions.assertEquals(t.count(), 1L); Assertions.assertEquals(t.totalTime(), 400L); } @Test public void testRecordSupplier() throws Exception { Timer t = new DefaultTimer(clock, NoopId.INSTANCE); clock.setMonotonicTime(100L); String value = t.recordSupplier(() -> { clock.setMonotonicTime(500L); return "foo"; }); Assertions.assertEquals(value, "foo"); Assertions.assertEquals(t.count(), 1L); Assertions.assertEquals(t.totalTime(), 400L); } @Test public void testRecordSupplierException() { Timer t = new DefaultTimer(clock, NoopId.INSTANCE); clock.setMonotonicTime(100L); boolean seen = false; try { t.recordSupplier(() -> { clock.setMonotonicTime(500L); throw new RuntimeException("foo"); }); } catch (Exception e) { seen = true; } Assertions.assertTrue(seen); Assertions.assertEquals(t.count(), 1L); Assertions.assertEquals(t.totalTime(), 400L); } @Test public void testRecordBooleanSupplier() { Timer t = new DefaultTimer(clock, NoopId.INSTANCE); clock.setMonotonicTime(100L); boolean value = t.recordBooleanSupplier(() -> { clock.setMonotonicTime(500L); return true; }); Assertions.assertTrue(value); Assertions.assertEquals(t.count(), 1L); Assertions.assertEquals(t.totalTime(), 400L); } @Test public void testRecordBooleanSupplierException() { Timer t = new DefaultTimer(clock, NoopId.INSTANCE); clock.setMonotonicTime(100L); boolean seen = false; try { t.recordBooleanSupplier(() -> { clock.setMonotonicTime(500L); throw new RuntimeException("foo"); }); } catch (Exception e) { seen = true; } Assertions.assertTrue(seen); Assertions.assertEquals(t.count(), 1L); Assertions.assertEquals(t.totalTime(), 400L); } @Test public void testRecordIntSupplier() { Timer t = new DefaultTimer(clock, NoopId.INSTANCE); clock.setMonotonicTime(100L); int value = t.recordIntSupplier(() -> { clock.setMonotonicTime(500L); return 42; }); Assertions.assertEquals(value, 42); Assertions.assertEquals(t.count(), 1L); Assertions.assertEquals(t.totalTime(), 400L); } @Test public void testRecordIntSupplierException() { Timer t = new DefaultTimer(clock, NoopId.INSTANCE); clock.setMonotonicTime(100L); boolean seen = false; try { t.recordIntSupplier(() -> { clock.setMonotonicTime(500L); throw new RuntimeException("foo"); }); } catch (Exception e) { seen = true; } Assertions.assertTrue(seen); Assertions.assertEquals(t.count(), 1L); Assertions.assertEquals(t.totalTime(), 400L); } @Test public void testRecordLongSupplier() { Timer t = new DefaultTimer(clock, NoopId.INSTANCE); clock.setMonotonicTime(100L); long value = t.recordLongSupplier(() -> { clock.setMonotonicTime(500L); return 42L; }); Assertions.assertEquals(value, 42L); Assertions.assertEquals(t.count(), 1L); Assertions.assertEquals(t.totalTime(), 400L); } @Test public void testRecordLongSupplierException() { Timer t = new DefaultTimer(clock, NoopId.INSTANCE); clock.setMonotonicTime(100L); boolean seen = false; try { t.recordLongSupplier(() -> { clock.setMonotonicTime(500L); throw new RuntimeException("foo"); }); } catch (Exception e) { seen = true; } Assertions.assertTrue(seen); Assertions.assertEquals(t.count(), 1L); Assertions.assertEquals(t.totalTime(), 400L); } @Test public void testRecordDoubleSupplier() { Timer t = new DefaultTimer(clock, NoopId.INSTANCE); clock.setMonotonicTime(100L); double value = t.recordDoubleSupplier(() -> { clock.setMonotonicTime(500L); return 42.5; }); Assertions.assertEquals(value, 42.5); Assertions.assertEquals(t.count(), 1L); Assertions.assertEquals(t.totalTime(), 400L); } @Test public void testRecordDoubleSupplierException() { Timer t = new DefaultTimer(clock, NoopId.INSTANCE); clock.setMonotonicTime(100L); boolean seen = false; try { t.recordDoubleSupplier(() -> { clock.setMonotonicTime(500L); throw new RuntimeException("foo"); }); } catch (Exception e) { seen = true; } Assertions.assertTrue(seen); Assertions.assertEquals(t.count(), 1L); Assertions.assertEquals(t.totalTime(), 400L); } @SuppressWarnings("unchecked") private <T> void testWrapper(Class<T> cls, BiFunction<Timer, T, T> wrap, Consumer<T> run, Object retValue) { clock.setMonotonicTime(0L); Timer t = new DefaultTimer(clock, NoopId.INSTANCE); clock.setMonotonicTime(100L); // Success T f = (T) Proxy.newProxyInstance( cls.getClassLoader(), new Class<?>[]{cls}, (obj, m, args) -> { clock.setMonotonicTime(500L); return retValue; } ); T wrapped = wrap.apply(t, f); Assertions.assertEquals(t.count(), 0L); run.accept(wrapped); Assertions.assertEquals(t.count(), 1L); Assertions.assertEquals(t.totalTime(), 400L); // Exception T f2 = (T) Proxy.newProxyInstance( cls.getClassLoader(), new Class<?>[]{cls}, (obj, m, args) -> { clock.setMonotonicTime(1000L); throw new RuntimeException("foo"); } ); final T wrapped2 = wrap.apply(t, f2); Assertions.assertThrows(RuntimeException.class, () -> run.accept(wrapped2)); Assertions.assertEquals(t.count(), 2L); Assertions.assertEquals(t.totalTime(), 900L); } @SuppressWarnings("unchecked") @Test public void testWrappingLambdas() { Consumer<Callable> cc = c -> { try { c.call(); } catch (Exception e) { throw new RuntimeException(e); } }; testWrapper(Callable.class, Timer::wrapCallable, cc, ""); testWrapper(Runnable.class, Timer::wrapRunnable, Runnable::run, ""); testWrapper(BiConsumer.class, Timer::wrapBiConsumer, c -> c.accept("", ""), ""); testWrapper(BiFunction.class, Timer::wrapBiFunction, c -> c.apply("", ""), ""); testWrapper(BinaryOperator.class, Timer::wrapBinaryOperator, c -> c.apply("", ""), ""); testWrapper(BiPredicate.class, Timer::wrapBiPredicate, c -> c.test("", ""), false); testWrapper(BooleanSupplier.class, Timer::wrapBooleanSupplier, BooleanSupplier::getAsBoolean, false); testWrapper(Consumer.class, Timer::wrapConsumer, c -> c.accept(""), ""); testWrapper(DoubleBinaryOperator.class, Timer::wrapDoubleBinaryOperator, c -> c.applyAsDouble(1.0, 2.0), 3.0); testWrapper(DoubleConsumer.class, Timer::wrapDoubleConsumer, c -> c.accept(1.0), ""); testWrapper(java.util.function.DoubleFunction.class, Timer::wrapDoubleFunction, c -> c.apply(1.0), 1.0); testWrapper(DoublePredicate.class, Timer::wrapDoublePredicate, c -> c.test(1.0), false); testWrapper(DoubleSupplier.class, Timer::wrapDoubleSupplier, DoubleSupplier::getAsDouble, 1.0); testWrapper(DoubleToIntFunction.class, Timer::wrapDoubleToIntFunction, c -> c.applyAsInt(1.0), 1); testWrapper(DoubleToLongFunction.class, Timer::wrapDoubleToLongFunction, c -> c.applyAsLong(1.0), 1L); testWrapper(DoubleUnaryOperator.class, Timer::wrapDoubleUnaryOperator, c -> c.applyAsDouble(1.0), 1.0); testWrapper(Function.class, Timer::wrapFunction, c -> c.apply(""), ""); testWrapper(IntBinaryOperator.class, Timer::wrapIntBinaryOperator, c -> c.applyAsInt(1, 2), 3); testWrapper(IntConsumer.class, Timer::wrapIntConsumer, c -> c.accept(1), ""); testWrapper(IntFunction.class, Timer::wrapIntFunction, c -> c.apply(1), 1); testWrapper(IntPredicate.class, Timer::wrapIntPredicate, c -> c.test(1), false); testWrapper(IntSupplier.class, Timer::wrapIntSupplier, IntSupplier::getAsInt, 1); testWrapper(IntToDoubleFunction.class, Timer::wrapIntToDoubleFunction, c -> c.applyAsDouble(1), 1.0); testWrapper(IntToLongFunction.class, Timer::wrapIntToLongFunction, c -> c.applyAsLong(1), 1L); testWrapper(IntUnaryOperator.class, Timer::wrapIntUnaryOperator, c -> c.applyAsInt(1), 1); testWrapper(LongBinaryOperator.class, Timer::wrapLongBinaryOperator, c -> c.applyAsLong(1, 2), 3L); testWrapper(LongConsumer.class, Timer::wrapLongConsumer, c -> c.accept(1), ""); testWrapper(LongFunction.class, Timer::wrapLongFunction, c -> c.apply(1), 1L); testWrapper(LongPredicate.class, Timer::wrapLongPredicate, c -> c.test(1), false); testWrapper(LongSupplier.class, Timer::wrapLongSupplier, LongSupplier::getAsLong, 1L); testWrapper(LongToDoubleFunction.class, Timer::wrapLongToDoubleFunction, c -> c.applyAsDouble(1), 1.0); testWrapper(LongToIntFunction.class, Timer::wrapLongToIntFunction, c -> c.applyAsInt(1), 1); testWrapper(LongUnaryOperator.class, Timer::wrapLongUnaryOperator, c -> c.applyAsLong(1), 1L); testWrapper(ObjDoubleConsumer.class, Timer::wrapObjDoubleConsumer, c -> c.accept("", 1.0), ""); testWrapper(ObjIntConsumer.class, Timer::wrapObjIntConsumer, c -> c.accept("", 1), ""); testWrapper(ObjLongConsumer.class, Timer::wrapObjLongConsumer, c -> c.accept("", 1L), ""); testWrapper(Predicate.class, Timer::wrapPredicate, c -> c.test(""), false); testWrapper(Supplier.class, Timer::wrapSupplier, Supplier::get, ""); testWrapper(ToDoubleBiFunction.class, Timer::wrapToDoubleBiFunction, c -> c.applyAsDouble("", ""), 1.0); testWrapper(ToDoubleFunction.class, Timer::wrapToDoubleFunction, c -> c.applyAsDouble(""), 1.0); testWrapper(ToIntBiFunction.class, Timer::wrapToIntBiFunction, c -> c.applyAsInt("", ""), 1); testWrapper(ToIntFunction.class, Timer::wrapToIntFunction, c -> c.applyAsInt(""), 1); testWrapper(ToLongBiFunction.class, Timer::wrapToLongBiFunction, c -> c.applyAsLong("", ""), 1L); testWrapper(ToLongFunction.class, Timer::wrapToLongFunction, c -> c.applyAsLong(""), 1L); testWrapper(UnaryOperator.class, Timer::wrapUnaryOperator, c -> c.apply(""), ""); } @Test public void wrapWithStreamApi() { Timer t = new DefaultTimer(clock, NoopId.INSTANCE); clock.setMonotonicTime(100L); int sum = Arrays .stream(new int[] {1, 2, 3, 4, 5, 6}) .map(t.wrapIntUnaryOperator(i -> i + 1)) .sum(); Assertions.assertEquals(27, sum); sum = Arrays .stream(new String[] {"foo", "bar", "baz"}) .mapToInt(t.wrapToIntFunction(String::length)) .sum(); Assertions.assertEquals(9, sum); } private int square(int v) { return v * v; } @Test public void testCallable() throws Exception { Timer t = new DefaultTimer(clock, NoopId.INSTANCE); int v2 = t.recordCallable(() -> square(42)); } @Test public void testMeasure() { Timer t = new DefaultTimer(clock, new DefaultId("foo")); t.record(42, TimeUnit.MILLISECONDS); clock.setWallTime(3712345L); for (Measurement m : t.measure()) { Assertions.assertEquals(m.timestamp(), 3712345L); if (m.id().equals(t.id().withTag(Statistic.count))) { Assertions.assertEquals(m.value(), 1.0, 0.1e-12); } else if (m.id().equals(t.id().withTag(Statistic.totalTime))) { Assertions.assertEquals(m.value(), 42e6, 0.1e-12); } else { Assertions.fail("unexpected id: " + m.id()); } } } }
5,712
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/NoopIdTest.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; public class NoopIdTest { @Test public void testTags() { Assertions.assertFalse(NoopId.INSTANCE.tags().iterator().hasNext()); } @Test public void testWithKeyValue() { Assertions.assertSame(NoopId.INSTANCE.withTag("k", "v"), NoopId.INSTANCE); } @Test public void testWithTag() { Assertions.assertSame(NoopId.INSTANCE.withTag(new BasicTag("k", "v")), NoopId.INSTANCE); } @Test public void testWithTags() { Assertions.assertSame(NoopId.INSTANCE.withTags(ArrayTagSet.create("k", "v")), NoopId.INSTANCE); } @Test public void testWithTagMap() { Map<String, String> tags = new HashMap<>(); tags.put("k", "v"); Assertions.assertSame(NoopId.INSTANCE.withTags(tags), NoopId.INSTANCE); } @Test public void testToString() { Assertions.assertEquals(NoopId.INSTANCE.toString(), "noop"); } }
5,713
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/ArrayTagSetTest.java
/* * Copyright 2014-2023 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.SortedMap; import java.util.Spliterator; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import java.util.stream.StreamSupport; public class ArrayTagSetTest { @Test public void equalsContractTest() { // NOTE: EqualsVerifier doesn't work with cached hash code ArrayTagSet ts1 = ArrayTagSet.create("k1", "v1"); ArrayTagSet ts2 = ArrayTagSet.create("k2", "v2").addAll(ts1); Assertions.assertEquals(ts1, ts1); Assertions.assertEquals(ts2, ts2); Assertions.assertNotEquals(ts1, null); Assertions.assertNotEquals(ts1, new Object()); Assertions.assertNotEquals(ts1, ArrayTagSet.create("k1", "v2")); Assertions.assertNotEquals(ts1, ArrayTagSet.create("k2", "v1")); Assertions.assertNotEquals(ts1, ArrayTagSet.create("k1", "v1").addAll(ts2)); Assertions.assertEquals(ts2, ArrayTagSet.create("k2", "v2").addAll(ts1)); Assertions.assertEquals(ts2, ArrayTagSet.create("k2", "v2").addAll(ArrayTagSet.create("k1", "v1"))); } @Test public void testHashCode() { Assertions.assertEquals(1, ArrayTagSet.EMPTY.hashCode()); Assertions.assertEquals(ArrayTagSet.create("k1", "v1", "k2", "v2"), ArrayTagSet.create("k2", "v2", "k1", "v1")); } @Test public void testToString() { ArrayTagSet ts1 = ArrayTagSet.create("k1", "v1"); ArrayTagSet ts2 = ArrayTagSet.create("k2", "v2").addAll(ts1); ArrayTagSet ts3 = ArrayTagSet.create("k3", "v3").addAll(ts2); Assertions.assertEquals(":k1=v1", ts1.toString()); Assertions.assertEquals(":k1=v1:k2=v2", ts2.toString()); Assertions.assertEquals(":k1=v1:k2=v2:k3=v3", ts3.toString()); } @Test public void testSingle() { ArrayTagSet ts = ArrayTagSet.create("k", "v"); for (Tag t : ts) { Assertions.assertEquals(t.key(), "k"); Assertions.assertEquals(t.value(), "v"); } } @Test public void testNullKey() { Assertions.assertThrows(NullPointerException.class, () -> ArrayTagSet.create(null, "v")); } @Test public void testNullValue() { Assertions.assertThrows(NullPointerException.class, () -> ArrayTagSet.create("k", null)); } @Test public void testAddNullKey() { ArrayTagSet ts = ArrayTagSet.EMPTY; Assertions.assertThrows(NullPointerException.class, () -> ts.add(null, "v")); } @Test public void testAddNullValue() { ArrayTagSet ts = ArrayTagSet.EMPTY; Assertions.assertThrows(NullPointerException.class, () -> ts.add("k", null)); } @Test public void testIteratorRemoveUnsupported() { Assertions.assertThrows(UnsupportedOperationException.class, () -> ArrayTagSet.create("k", "v").iterator().remove()); } @Test public void testIteratorNext() { Assertions.assertThrows(NoSuchElementException.class, () -> { ArrayTagSet tag = ArrayTagSet.create("k", "v"); Iterator<Tag> iter = tag.iterator(); Assertions.assertTrue(iter.hasNext()); Assertions.assertEquals(new BasicTag("k", "v"), iter.next()); Assertions.assertFalse(iter.hasNext()); iter.next(); }); } @Test public void testCreateFromMap() { Map<String, String> m = new HashMap<>(); m.put("k", "v"); ArrayTagSet ts1 = ArrayTagSet.create(m); ArrayTagSet ts2 = ArrayTagSet.create("k", "v"); Assertions.assertEquals(ts1, ts2); } @Test public void testCreateFromMapWithMultipleValues() { Map<String, String> m = new HashMap<>(); m.put("k1", "v1"); m.put("k2", "v2"); ArrayTagSet ts1 = ArrayTagSet.create(m); ArrayTagSet ts2 = ArrayTagSet.create("k1", "v1").addAll(ArrayTagSet.create("k2", "v2")); Assertions.assertEquals(ts1, ts2); } @Test public void testCreateFromArrayTagSet() { ArrayTagSet ts = ArrayTagSet.create("k", "v"); ArrayTagSet ts1 = ArrayTagSet.create(ts); ArrayTagSet ts2 = ArrayTagSet.create("k", "v"); Assertions.assertEquals(ts1, ts2); } @Test public void testCreateFromVarargs2() { Map<String, String> m = new HashMap<>(); m.put("k1", "v1"); m.put("k2", "v2"); ArrayTagSet ts1 = ArrayTagSet.create(m); ArrayTagSet ts2 = ArrayTagSet.create("k1", "v1", "k2", "v2"); Assertions.assertEquals(ts1, ts2); } @Test public void testCreateFromVarargs5() { Map<String, String> m = new HashMap<>(); m.put("a", "1"); m.put("b", "2"); m.put("c", "3"); m.put("d", "4"); m.put("e", "5"); ArrayTagSet ts1 = ArrayTagSet.create(m); ArrayTagSet ts2 = ArrayTagSet.create("a", "1", "b", "2", "c", "3", "d", "4", "e", "5"); Assertions.assertEquals(ts1, ts2); } @Test public void testCreateFromVarargsOdd() { Assertions.assertThrows(IllegalArgumentException.class, () -> ArrayTagSet.create("a", "1", "b")); } @Test public void testCreateFromEmptyIterable() { Assertions.assertEquals(ArrayTagSet.EMPTY, ArrayTagSet.create(Collections.emptyList())); } @Test public void testCreateFromSingleValueIterable() { Collection<Tag> coll = Collections.singleton(new BasicTag("k", "v")); ArrayTagSet ts1 = ArrayTagSet.create(coll); ArrayTagSet ts2 = ArrayTagSet.create("k", "v"); Assertions.assertEquals(ts1, ts2); } @Test public void testCreateFromMultiValueIterable() { List<Tag> coll = new ArrayList<>(); coll.add(new BasicTag("k1", "v1")); coll.add(new BasicTag("k2", "v2")); ArrayTagSet ts1 = ArrayTagSet.create(coll); ArrayTagSet ts2 = ArrayTagSet.create("k1", "v1").addAll(ArrayTagSet.create("k2", "v2")); Assertions.assertEquals(ts1, ts2); } @Test public void testCreateFromEmptyMap() { Assertions.assertEquals(ArrayTagSet.EMPTY, ArrayTagSet.create(Collections.emptyMap())); } @Test public void testCreateFromSingleValueMap() { Map<String, String> tags = new HashMap<>(); tags.put("k", "v"); Assertions.assertEquals(ArrayTagSet.create("k", "v"), ArrayTagSet.create(tags)); } @Test public void testCreateFromMultiValueMap() { Map<String, String> tags = new HashMap<>(); tags.put("k1", "v1"); tags.put("k2", "v2"); Assertions.assertEquals(ArrayTagSet.create("k1", "v1") .addAll(ArrayTagSet.create("k2", "v2")), ArrayTagSet.create(tags)); } @Test public void testMergeNullTag() { Assertions.assertThrows(NullPointerException.class, () -> { ArrayTagSet expected = ArrayTagSet.create("k", "v"); expected.add(null); }); } @Test public void testMergeTag() { ArrayTagSet initial = ArrayTagSet.create("k2", "v2"); ArrayTagSet update = ArrayTagSet.create("k1", "v1"); ArrayTagSet expected = ArrayTagSet.create("k1", "v1").addAll(ArrayTagSet.create("k2", "v2")); Assertions.assertEquals(expected, initial.addAll(update)); } @Test public void testMergeWithSelf() { ArrayTagSet tags = ArrayTagSet.create("k1", "v1"); ArrayTagSet updated = tags.addAll(tags); Assertions.assertSame(tags, updated); } @Test public void testMergeWithEmpty() { ArrayTagSet tags = ArrayTagSet.create("k1", "v1"); ArrayTagSet updated = tags.addAll(ArrayTagSet.EMPTY); Assertions.assertSame(tags, updated); } @Test public void testEmptyMergeWithNonEmpty() { ArrayTagSet tags = ArrayTagSet.create("k1", "v1"); ArrayTagSet updated = ArrayTagSet.EMPTY.addAll(tags); Assertions.assertSame(tags, updated); } @Test public void testMergeTagWithSameKey() { ArrayTagSet initial = ArrayTagSet.create("k1", "v1"); ArrayTagSet expected = ArrayTagSet.create("k1", "v2"); ArrayTagSet actual = initial.addAll(expected); Assertions.assertNotSame(expected, actual); Assertions.assertEquals(expected, actual); } @Test public void testMergeNullList() { Assertions.assertThrows(NullPointerException.class, () -> { ArrayTagSet expected = ArrayTagSet.create("k3", "v3"); expected.addAll((Iterable<Tag>) null); }); } @Test public void testMergeEmptyList() { ArrayTagSet expected = ArrayTagSet.create("k3", "v3"); ArrayTagSet actual = expected.addAll(new ArrayList<>()); Assertions.assertSame(expected, actual); } @Test public void testMergeSingleValueAsList() { ArrayList<Tag> prefix = new ArrayList<>(); ArrayTagSet initial = ArrayTagSet.create("k3", "v3"); ArrayTagSet expected = ArrayTagSet.create("k1", "v1").addAll(ArrayTagSet.create("k3", "v3")); prefix.add(new BasicTag("k1", "v1")); ArrayTagSet actual = initial.addAll(prefix); Assertions.assertEquals(expected, actual); } @Test public void testMergeMultipleValuesAsList() { ArrayList<Tag> prefix = new ArrayList<>(); ArrayTagSet initial = ArrayTagSet.create("k3", "v3"); ArrayTagSet expected = ArrayTagSet.create("k1", "v1") .addAll(ArrayTagSet.create("k2", "v2")) .addAll(ArrayTagSet.create("k3", "v3")); prefix.add(new BasicTag("k1", "v1")); prefix.add(new BasicTag("k2", "v2")); ArrayTagSet actual = initial.addAll(prefix); Assertions.assertEquals(expected, actual); } @Test public void testMergeNullMap() { Assertions.assertThrows(NullPointerException.class, () -> { ArrayTagSet expected = ArrayTagSet.create("k3", "v3"); expected.addAll((Map<String, String>) null); }); } @Test public void testMergeEmptyMap() { ArrayTagSet expected = ArrayTagSet.create("k3", "v3"); ArrayTagSet actual = expected.addAll(new HashMap<>()); Assertions.assertSame(expected, actual); } @Test public void testMergeSingleValueAsMap() { Map<String, String> extra = new HashMap<>(); ArrayTagSet initial = ArrayTagSet.create("k3", "v3"); ArrayTagSet expected = ArrayTagSet.create("k1", "v1").addAll(ArrayTagSet.create("k3", "v3")); extra.put("k1", "v1"); ArrayTagSet actual = initial.addAll(extra); Assertions.assertEquals(expected, actual); } @Test public void testMergeMultipleValuesAsMap() { Map<String, String> extra = new HashMap<>(); ArrayTagSet initial = ArrayTagSet.create("k3", "v3"); ArrayTagSet expected = ArrayTagSet.create("k1", "v1") .addAll(ArrayTagSet.create("k2", "v2")) .addAll(ArrayTagSet.create("k3", "v3")); extra.put("k1", "v1"); extra.put("k2", "v2"); ArrayTagSet actual = initial.addAll(extra); Assertions.assertEquals(expected, actual); } @Test public void addAllTagArrayEmpty() { ArrayTagSet ts = ArrayTagSet.EMPTY.addAll(new Tag[0]); Assertions.assertSame(ArrayTagSet.EMPTY, ts); } @Test public void addAllStringArrayEmpty() { ArrayTagSet ts = ArrayTagSet.EMPTY.addAll(new String[0]); Assertions.assertSame(ArrayTagSet.EMPTY, ts); } @Test public void addAllStringArrayMutate() { String[] vs = {"a", "b"}; ArrayTagSet ts = ArrayTagSet.EMPTY.addAll(vs); vs[0] = "c"; Assertions.assertEquals(ArrayTagSet.create("a", "b"), ts); } @Test public void addAllIterable() { // Add an arbitrary iterable that isn't a collection or ArrayTagSet Collection<Tag> tags = Collections.singletonList(new BasicTag("app", "foo")); ArrayTagSet ts = ArrayTagSet.EMPTY.addAll(tags::iterator); Assertions.assertEquals(ArrayTagSet.EMPTY.addAll(tags), ts); } @Test public void addAllDedupEmpty() { ArrayTagSet ts = ArrayTagSet.EMPTY.addAll(new String[] {"a", "1", "a", "2", "a", "3"}); Assertions.assertEquals(ArrayTagSet.EMPTY.add(new BasicTag("a", "3")), ts); } @Test public void addAllDedupMerge() { ArrayTagSet ts = ArrayTagSet.EMPTY .addAll(new String[] {"a", "1", "a", "2", "a", "3"}) .addAll(new String[] {"a", "4", "a", "5", "a", "6", "b", "1"}); ArrayTagSet expected = ArrayTagSet.EMPTY .add(new BasicTag("a", "6")) .add(new BasicTag("b", "1")); Assertions.assertEquals(expected, ts); } @Test public void tagListIterate() { ArrayTagSet expected = ArrayTagSet.create("a", "1", "b", "2", "c", "3", "d", "4", "e", "5"); ArrayTagSet actual = ArrayTagSet.EMPTY; for (Tag t : expected) { actual = actual.add(t); } Assertions.assertEquals(expected, actual); } @Test public void tagListForEach() { ArrayTagSet expected = ArrayTagSet.create("a", "1", "b", "2", "c", "3", "d", "4", "e", "5"); List<Tag> tmp = new ArrayList<>(); expected.forEach((k, v) -> tmp.add(Tag.of(k, v))); Assertions.assertEquals(expected, ArrayTagSet.create(tmp)); } @Test public void tagListFilter() { ArrayTagSet filtered = ArrayTagSet .create("a", "1", "b", "2", "c", "3") .filter((k, v) -> !v.equals("2")); Assertions.assertEquals(ArrayTagSet.create("a", "1", "c", "3"), filtered); } @Test public void tagListFilterMatchAll() { ArrayTagSet filtered = ArrayTagSet .create("a", "1", "b", "2", "c", "3") .filter((k, v) -> true); Assertions.assertEquals(ArrayTagSet.create("a", "1", "b", "2", "c", "3"), filtered); } @Test public void tagListFilterMatchNone() { ArrayTagSet filtered = ArrayTagSet .create("a", "1", "b", "2", "c", "3") .filter((k, v) -> false); Assertions.assertEquals(ArrayTagSet.EMPTY, filtered); } @Test public void tagListFilterByKey() { ArrayTagSet filtered = ArrayTagSet .create("a", "1", "b", "2", "c", "3") .filterByKey(k -> !k.equals("b")); Assertions.assertEquals(ArrayTagSet.create("a", "1", "c", "3"), filtered); } @Test public void tagListFilterByKeyMatchAll() { ArrayTagSet filtered = ArrayTagSet .create("a", "1", "b", "2", "c", "3") .filterByKey(k -> true); Assertions.assertEquals(ArrayTagSet.create("a", "1", "b", "2", "c", "3"), filtered); } @Test public void tagListFilterByKeyMatchNone() { ArrayTagSet filtered = ArrayTagSet .create("a", "1", "b", "2", "c", "3") .filterByKey(k -> false); Assertions.assertEquals(ArrayTagSet.EMPTY, filtered); } @Test public void addAllConcurrentMap() { Map<String, String> tags = new ConcurrentHashMap<>(); tags.put("app", "foo"); ArrayTagSet ts = ArrayTagSet.EMPTY.addAll(tags); Assertions.assertEquals(ArrayTagSet.EMPTY.add("app", "foo"), ts); } @Test public void addAllConcurrentMapFailure() throws InterruptedException { // This test just checks that we do not throw if the map is being modified concurrently. // It seems to fail reliably when testing prior to the patch. // https://github.com/Netflix/spectator/issues/733 final AtomicBoolean done = new AtomicBoolean(false); final Map<String, String> tags = new ConcurrentHashMap<>(); Thread t1 = new Thread(() -> { while (!done.get()) { tags.remove("app"); } }); t1.start(); Thread t2 = new Thread(() -> { while (!done.get()) { tags.put("app", "foo"); } }); t2.start(); try { for (int i = 0; i < 10_000; ++i) { ArrayTagSet.EMPTY.addAll(tags); } } finally { done.set(true); t1.join(); t2.join(); } } @Test public void compareToEmpty() { Assertions.assertEquals(0, ArrayTagSet.EMPTY.compareTo(ArrayTagSet.EMPTY)); } @Test public void compareToEquals() { ArrayTagSet a = ArrayTagSet.create("a", "1", "b", "2", "c", "3"); ArrayTagSet b = ArrayTagSet.create("a", "1", "b", "2", "c", "3"); Assertions.assertEquals(0, a.compareTo(b)); } @Test public void compareToDifferentKeys() { ArrayTagSet a = ArrayTagSet.create("a", "1", "b", "2", "c", "3"); ArrayTagSet b = ArrayTagSet.create("a", "1", "d", "2", "c", "3"); Assertions.assertEquals(-1, a.compareTo(b)); Assertions.assertEquals(1, b.compareTo(a)); } @Test public void compareToDifferentValues() { ArrayTagSet a = ArrayTagSet.create("a", "1", "b", "3", "c", "3"); ArrayTagSet b = ArrayTagSet.create("a", "1", "b", "2", "c", "3"); Assertions.assertEquals(1, a.compareTo(b)); Assertions.assertEquals(-1, b.compareTo(a)); } @Test public void compareToDifferentSizes() { ArrayTagSet a = ArrayTagSet.create("a", "1", "b", "2", "c", "3"); ArrayTagSet b = ArrayTagSet.create("a", "1", "b", "2", "c", "3", "d", "4"); Assertions.assertEquals(-1, a.compareTo(b)); Assertions.assertEquals(1, b.compareTo(a)); } @Test public void mergeTagList() { TagList tagList = new TagList() { @Override public String getKey(int i) { return "k" + ++i; } @Override public String getValue(int i) { return "v" + ++i; } @Override public int size() { return 3; } }; ArrayTagSet tags = ArrayTagSet.create("k1", "v1", "k2", "v2"); ArrayTagSet updated = tags.addAll(tagList); ArrayTagSet expected = ArrayTagSet.create("k1", "v1", "k2", "v2", "k3", "v3"); Assertions.assertEquals(expected, updated); } @Test public void mergeEmptyTagList() { TagList empty = new TagList() { @Override public String getKey(int i) { throw new IndexOutOfBoundsException(); } @Override public String getValue(int i) { throw new IndexOutOfBoundsException(); } @Override public int size() { return 0; } }; ArrayTagSet tags = ArrayTagSet.create("k1", "v1", "k2", "v2"); ArrayTagSet updated = tags.addAll(empty); Assertions.assertSame(tags, updated); } @Test public void spliteratorSizeAndCharacteristics() { ArrayTagSet tags = ArrayTagSet.create("k1", "v1", "k2", "v2", "k3", "v3"); Spliterator<Tag> spliterator = tags.spliterator(); Assertions.assertTrue(spliterator.hasCharacteristics(Spliterator.IMMUTABLE)); Assertions.assertTrue(spliterator.hasCharacteristics(Spliterator.ORDERED)); Assertions.assertTrue(spliterator.hasCharacteristics(Spliterator.SORTED)); Assertions.assertTrue(spliterator.hasCharacteristics(Spliterator.NONNULL)); Assertions.assertTrue(spliterator.hasCharacteristics(Spliterator.SIZED)); Assertions.assertEquals(3L, spliterator.getExactSizeIfKnown()); } @Test public void testCreateWithSortedMap() { SortedMap<String, String> tagMap = new TreeMap<>(); tagMap.put("a", "v1"); tagMap.put("b", "v2"); tagMap.put("c", "v3"); tagMap.put("d", "v4"); ArrayTagSet tags = ArrayTagSet.create(tagMap); List<Tag> tagList = StreamSupport.stream(tags.spliterator(), false).collect(Collectors.toList()); Assertions.assertEquals(Arrays.asList(Tag.of("a", "v1"), Tag.of("b", "v2"), Tag.of("c", "v3"), Tag.of("d", "v4")), tagList); } @Test public void testCreateWithSortedMapCustomComparator() { SortedMap<String, String> tagMap = new TreeMap<>(Comparator.reverseOrder()); tagMap.put("a", "v1"); tagMap.put("b", "v2"); tagMap.put("c", "v3"); tagMap.put("d", "v4"); ArrayTagSet tags = ArrayTagSet.create(tagMap); List<Tag> tagList = StreamSupport.stream(tags.spliterator(), false).collect(Collectors.toList()); Assertions.assertEquals(Arrays.asList(Tag.of("a", "v1"), Tag.of("b", "v2"), Tag.of("c", "v3"), Tag.of("d", "v4")), tagList); } @Test public void testCreateWithSortedMapCustomComparatorNaturalOrder() { SortedMap<String, String> tagMap = new TreeMap<>(Comparator.naturalOrder()); tagMap.put("a", "v1"); tagMap.put("b", "v2"); tagMap.put("c", "v3"); tagMap.put("d", "v4"); ArrayTagSet tags = ArrayTagSet.create(tagMap); List<Tag> tagList = StreamSupport.stream(tags.spliterator(), false).collect(Collectors.toList()); Assertions.assertEquals(Arrays.asList(Tag.of("a", "v1"), Tag.of("b", "v2"), Tag.of("c", "v3"), Tag.of("d", "v4")), tagList); } @Test public void addReplace() { ArrayTagSet ts1 = ArrayTagSet.create("k1", "v1"); ArrayTagSet ts2 = ArrayTagSet.create("k1", "v2"); ArrayTagSet expected = ArrayTagSet.create("k1", "v2"); Assertions.assertEquals(expected, ts1.addAll(ts2)); List<Tag> list = new ArrayList<>(); list.add(new BasicTag("k1", "v3")); list.add(new BasicTag("k1", "v2")); Assertions.assertEquals(expected, ts1.addAll(list)); list.clear(); list.add(new BasicTag("k1", "v3")); list.add(new BasicTag("k1", "v2")); Assertions.assertEquals(expected, ArrayTagSet.create(new HashMap<>()).addAll(list)); Assertions.assertEquals(expected, expected.addAll(new ArrayList<>())); Assertions.assertEquals(expected, expected.addAll(new HashMap<>())); Assertions.assertEquals(expected, ts1.addAll(new BadTagList("k1", "v2"))); Assertions.assertEquals(expected, ts1.addAll(new TagIterator("k1", "v2"))); Assertions.assertEquals(expected, ts1.addAll(new Tag[] { new BasicTag("k1", "v2")})); ConcurrentHashMap<String, String> cMap = new ConcurrentHashMap<>(); cMap.put("k1", "v2"); Assertions.assertEquals(expected, ts1.addAll(cMap)); HashMap<String, String> hMap = new HashMap<>(); hMap.put("k1", "v2"); Assertions.assertEquals(expected, ts1.addAll(hMap)); Assertions.assertEquals(expected, ts1.add("k1", "v2")); Assertions.assertEquals(expected, ts1.add(new BasicTag("k1", "v2"))); Assertions.assertEquals(expected, ArrayTagSet.create("k1", "v1", "k1", "v2")); } @Test public void testAddBeginning() { ArrayTagSet tags = ArrayTagSet.create("a", "v1", "b", "v2", "c", "v3"); ArrayTagSet updated = tags.add("0", "v0"); Assertions.assertEquals(ArrayTagSet.create("0", "v0", "a", "v1", "b", "v2", "c", "v3"), updated); } @Test public void testAddEnd() { ArrayTagSet tags = ArrayTagSet.create("a", "v1", "b", "v2", "c", "v3"); ArrayTagSet updated = tags.add("d", "v4"); Assertions.assertEquals(ArrayTagSet.create("a", "v1", "b", "v2", "c", "v3", "d", "v4"), updated); } @Test public void testAddMiddle() { ArrayTagSet tags = ArrayTagSet.create("a", "v1", "b", "v2", "d", "v4"); ArrayTagSet updated = tags.add("c", "v3"); Assertions.assertEquals(ArrayTagSet.create("a", "v1", "b", "v2", "c", "v3", "d", "v4"), updated); } @Test public void testAddUpdatesExisting() { ArrayTagSet tags = ArrayTagSet.create("a", "v1", "b", "v2", "c", "v3"); ArrayTagSet updated = tags.add("c", "v3-updated"); Assertions.assertEquals(ArrayTagSet.create("a", "v1", "b", "v2", "c", "v3-updated"), updated); } @Test public void testAddUpdatesExistingWithSameTag() { ArrayTagSet tags = ArrayTagSet.create("a", "v1", "b", "v2", "c", "v3"); ArrayTagSet updated = tags.add("c", "v3"); Assertions.assertSame(tags, updated); } @Test public void mergeDuplicatesTwoKeys() { String[] dst = new String[8]; String[] srcA = {"a", "2"}; String[] srcB = {"a", "1", "b", "1", "b", "2"}; int n = ArrayTagSet.merge(dst, srcA, srcA.length, srcB, srcB.length); Assertions.assertArrayEquals(new String[] {"a", "1", "b", "2", null, null, null, null}, dst); Assertions.assertEquals(4, n); } @Test public void mergeDuplicatesSrcB() { String[] dst = new String[8]; String[] srcA = {"b", "1"}; String[] srcB = {"a", "1", "a", "2"}; int n = ArrayTagSet.merge(dst, srcA, srcA.length, srcB, srcB.length); Assertions.assertArrayEquals(new String[] {"a", "2", "b", "1", null, null, null, null}, dst); Assertions.assertEquals(4, n); } @Test public void mergeDuplicatesBoth() { String[] dst = new String[8]; String[] srcA = {"a", "1"}; String[] srcB = {"a", "2", "a", "3"}; int n = ArrayTagSet.merge(dst, srcA, srcA.length, srcB, srcB.length); Assertions.assertArrayEquals(new String[] {"a", "3", null, null, null, null, null, null}, dst); Assertions.assertEquals(2, n); } @Test public void addAllDuplicates() { ArrayTagSet existing = ArrayTagSet.create("a", "foo"); List<Tag> tags = Arrays.asList( Tag.of("b", "bar"), Tag.of("b", "ERROR") ); ArrayTagSet updated = existing.addAll(tags); assertDistinct(updated); // <= 1.6.9 would throw here as the two values in the array list would be merged // into the result without checking for duplicates. existing = ArrayTagSet.create("b", "foo"); tags = Arrays.asList( Tag.of("a", "bar"), Tag.of("a", "ERROR") ); updated = existing.addAll(tags); assertDistinct(updated); existing = ArrayTagSet.create("b", "foo"); tags = Arrays.asList( Tag.of("a", "bar"), Tag.of("b", "boo"), Tag.of("a", "ERROR") ); updated = existing.addAll(tags); assertDistinct(updated); } class TagIterator implements Iterable<Tag> { String[] tags; TagIterator(String... tags) { this.tags = tags; } @Override public Iterator<Tag> iterator() { return new Iterator<Tag>() { int i = 0; @Override public boolean hasNext() { return i < tags.length; } @Override public Tag next() { return new BasicTag(tags[i++], tags[i++]); } }; } } class BadTagList implements TagList { String[] tags; BadTagList(String... tags) { this.tags = tags; } @Override public String getKey(int i) { return tags[i * 2]; } @Override public String getValue(int i) { return tags[(i * 2) + 1]; } @Override public int size() { return tags.length / 2; } } private void assertDistinct(TagList tags) { try { StreamSupport.stream(tags.spliterator(), false) .collect(Collectors.toMap(Tag::key, Tag::value)); } catch (Exception e) { throw new AssertionError("failed to convert tags to map", e); } } }
5,714
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/CompositeRegistryTest.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import com.netflix.spectator.api.patterns.PolledMeter; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.concurrent.TimeUnit; public class CompositeRegistryTest { private final ManualClock clock = new ManualClock(); private Registry newRegistry(int n, boolean warnings) { CompositeRegistry registry = new CompositeRegistry(clock); for (int i = 0; i < n; ++i) { registry.add(new DefaultRegistry(clock, new TestRegistryConfig(warnings, 10000))); } return registry; } @Test public void testInit() { CompositeRegistry registry = new CompositeRegistry(clock); Assertions.assertSame(clock, registry.clock()); } @Test public void testCreateId() { Registry r = newRegistry(5, true); Assertions.assertEquals(r.createId("foo"), new DefaultId("foo")); } @Test public void testCreateIdWithTags() { Registry r = newRegistry(5, true); ArrayTagSet ts = ArrayTagSet.create("k", "v"); Assertions.assertEquals(r.createId("foo", ts), new DefaultId("foo", ts)); } @Test public void testRegister() { Registry r = newRegistry(5, true); Counter c = new DefaultCounter(clock, r.createId("foo")); r.register(c); c.increment(); Assertions.assertEquals(c.count(), 1L); r.register(c); PolledMeter.update(r); Meter meter = r.get(c.id()); for (Measurement m : meter.measure()) { Assertions.assertEquals(m.value(), 2.0, 1e-12); } } @Test public void testCounter() { Registry r = newRegistry(5, true); Counter c = r.counter(r.createId("foo")); c.increment(); Assertions.assertEquals(c.count(), 1L); Counter c2 = r.counter(r.createId("foo")); Assertions.assertEquals(c.count(), c2.count()); } @Test public void testTimer() { Registry r = newRegistry(5, true); Timer t = r.timer(r.createId("foo")); t.record(42L, TimeUnit.MILLISECONDS); Assertions.assertEquals(t.count(), 1L); Timer t2 = r.timer(r.createId("foo")); Assertions.assertEquals(t.totalTime(), t2.totalTime()); } @Test public void testDistributionSummary() { Registry r = newRegistry(5, true); DistributionSummary t = r.distributionSummary(r.createId("foo")); t.record(42L); Assertions.assertEquals(t.count(), 1L); DistributionSummary t2 = r.distributionSummary(r.createId("foo")); Assertions.assertEquals(t.totalAmount(), t2.totalAmount()); } @Test public void testCounterBadTypeAccess() { Assertions.assertThrows(IllegalStateException.class, () -> { Registry r = newRegistry(5, true); r.counter(r.createId("foo")).count(); r.distributionSummary(r.createId("foo")).count(); }); } @Test public void testTimerBadTypeAccess() { Assertions.assertThrows(IllegalStateException.class, () -> { Registry r = newRegistry(5, true); r.timer(r.createId("foo")).count(); r.counter(r.createId("foo")).count(); }); } @Test public void testDistributionSummaryBadTypeAccess() { Assertions.assertThrows(IllegalStateException.class, () -> { Registry r = newRegistry(5, true); r.distributionSummary(r.createId("foo")).count(); r.timer(r.createId("foo")).count(); }); } @Test public void testRegisterBadTypeAccessNoThrow() { Registry r = newRegistry(5, false); Counter c = new DefaultCounter(clock, r.createId("foo")); r.counter(c.id()); r.register(c); Assertions.assertNotSame(r.get(c.id()), c); } @Test public void testCounterBadTypeAccessNoThrow() { Registry r = newRegistry(5, false); r.counter(r.createId("foo")).count(); Counter c = r.counter("foo"); DistributionSummary ds = r.distributionSummary(r.createId("foo")); ds.record(42); Assertions.assertEquals(ds.count(), 0L); } @Test public void testTimerBadTypeAccessNoThrow() { Registry r = newRegistry(5, false); r.timer(r.createId("foo")).count(); Counter c = r.counter(r.createId("foo")); c.increment(); Assertions.assertEquals(c.count(), 0L); } @Test public void testDistributionSummaryBadTypeAccessNoThrow() { Registry r = newRegistry(5, false); r.distributionSummary(r.createId("foo")).count(); Counter c = r.counter(r.createId("foo")); c.increment(); Assertions.assertEquals(c.count(), 0L); } @Test public void testGet() { Registry r = newRegistry(5, true); Counter c = r.counter(r.createId("foo")); c.increment(42); Meter m = r.get(c.id()); Assertions.assertEquals(c.measure().iterator().next(), m.measure().iterator().next()); } @Test public void testIteratorEmpty() { Registry r = newRegistry(5, true); for (Meter m : r) { Assertions.fail("should be empty, but found " + m.id()); } } @Test public void testIteratorDoesNotAllowRemove() { Assertions.assertThrows(UnsupportedOperationException.class, () -> { Registry r = newRegistry(5, true); Iterator<Meter> iter = r.iterator(); iter.remove(); }); } @Test public void testIterator() { // We need to increment because forwarding the registration to sub-registries is lazy and // will not occur if there is no activity Registry r = newRegistry(5, true); r.counter(r.createId("foo")).increment(); r.counter(r.createId("bar")).increment(); Set<Id> expected = new HashSet<>(); expected.add(r.createId("foo")); expected.add(r.createId("bar")); for (Meter m : r) { expected.remove(m.id()); } Assertions.assertTrue(expected.isEmpty()); } @Test public void testIteratorNoRegistries() { Registry r = newRegistry(0, true); r.counter(r.createId("foo")).increment(); Assertions.assertFalse(r.iterator().hasNext()); } @Test public void testAddAndRemove() { CompositeRegistry r = new CompositeRegistry(clock); Counter c1 = r.counter("id1"); c1.increment(); Assertions.assertEquals(0, c1.count()); Registry r1 = new DefaultRegistry(clock); r.add(r1); c1.increment(); Assertions.assertEquals(1, c1.count()); Registry r2 = new DefaultRegistry(clock); r.add(r2); c1.increment(); Assertions.assertEquals(2, r1.counter("id1").count()); Assertions.assertEquals(1, r2.counter("id1").count()); r.remove(r1); c1.increment(5); Assertions.assertEquals(2, r1.counter("id1").count()); Assertions.assertEquals(6, r2.counter("id1").count()); } @Test public void testHasExpired() { CompositeRegistry r = new CompositeRegistry(clock); Counter c1 = r.counter("id1"); Assertions.assertFalse(c1.hasExpired()); Registry r1 = new DefaultRegistry(clock); r.add(r1); Assertions.assertTrue(c1.hasExpired()); c1.increment(); Assertions.assertFalse(c1.hasExpired()); } @Test public void testAddGauges() { CompositeRegistry r = new CompositeRegistry(clock); Id id = r.createId("id1"); DefaultCounter c1 = new DefaultCounter(clock, id); c1.increment(); Registry r1 = new DefaultRegistry(clock); r.add(r1); for (Meter meter : r1) { for (Measurement m : meter.measure()) { Assertions.assertEquals(id, m.id()); } } } @Test public void correctTypeForCountersStream() { Registry r = newRegistry(5, false); r.counter("a").increment(); r.counter("b").increment(); Assertions.assertEquals(2, r.counters().count()); Assertions.assertEquals(2, r.stream().filter(m -> m instanceof Counter).count()); } @Test public void correctTypeForTimersStream() { Registry r = newRegistry(5, false); r.timer("a").record(1, TimeUnit.MICROSECONDS); r.timer("b").record(1, TimeUnit.MICROSECONDS); Assertions.assertEquals(2, r.timers().count()); Assertions.assertEquals(2, r.stream().filter(m -> m instanceof Timer).count()); } @Test public void correctTypeForDistSummariesStream() { Registry r = newRegistry(5, false); r.distributionSummary("a").record(1); r.distributionSummary("b").record(1); Assertions.assertEquals(2, r.distributionSummaries().count()); Assertions.assertEquals(2, r.stream().filter(m -> m instanceof DistributionSummary).count()); } @Test public void correctTypeForGaugesStream() { Registry r = newRegistry(5, false); r.gauge(r.createId("a")).set(1.0); r.gauge(r.createId("b")).set(2.0); Assertions.assertEquals(2, r.gauges().count()); Assertions.assertEquals(2, r.stream().filter(m -> m instanceof Gauge).count()); } @Test public void dedupAddedRegistries() { CompositeRegistry registry = new CompositeRegistry(clock); Registry r = new DefaultRegistry(); registry.add(r); registry.add(r); registry.counter("test").increment(); Assertions.assertEquals(1, r.counter("test").count()); } @Test public void meterLookupAfterRegistryChange() { CompositeRegistry r = new CompositeRegistry(clock); Registry r1 = new DefaultRegistry(clock); Registry r2 = new DefaultRegistry(clock); Counter c = r.counter("test"); c.increment(); Assertions.assertEquals(0, r1.counter("test").count()); Assertions.assertEquals(0, r2.counter("test").count()); r.add(r1); c.increment(); Assertions.assertEquals(1, r1.counter("test").count()); Assertions.assertEquals(0, r2.counter("test").count()); r.add(r2); c.increment(); Assertions.assertEquals(2, r1.counter("test").count()); Assertions.assertEquals(1, r2.counter("test").count()); r.remove(r1); c.increment(); Assertions.assertEquals(2, r1.counter("test").count()); Assertions.assertEquals(2, r2.counter("test").count()); } }
5,715
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/patterns/TagsBuilderTest.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api.patterns; import com.netflix.spectator.api.BasicTag; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Tag; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; public class TagsBuilderTest { private static final Registry REGISTRY = new DefaultRegistry(); private static Id newId(Iterable<Tag> tags) { return REGISTRY.createId("test").withTags(tags); } private static Id newId(String... tags) { return REGISTRY.createId("test").withTags(tags); } private static class Builder extends TagsBuilder<Builder> { Builder() { super(); } Id build() { return newId(extraTags); } } private enum Level { info, error } @Test public void stringKeyValue() { Id id = new Builder() .withTag("k", "v") .build(); Assertions.assertEquals(newId("k", "v"), id); } @Test public void booleanTrueValue() { Id id = new Builder() .withTag("k", true) .build(); Assertions.assertEquals(newId("k", "true"), id); } @Test public void booleanFalseValue() { Id id = new Builder() .withTag("k", false) .build(); Assertions.assertEquals(newId("k", "false"), id); } @Test public void enumValue() { Id id = new Builder() .withTag("k1", Level.info) .withTag("k2", Level.error) .build(); Assertions.assertEquals(newId("k1", "info", "k2", "error"), id); } @Test public void tag() { Id id = new Builder() .withTag(new BasicTag("k", "v")) .build(); Assertions.assertEquals(newId("k", "v"), id); } @Test public void varargStrings() { Id id = new Builder() .withTags("k1", "v1", "k2", "v2") .build(); Assertions.assertEquals(newId("k1", "v1", "k2", "v2"), id); } @Test public void varargTags() { Id id = new Builder() .withTags(new BasicTag("k1", "v1"), new BasicTag("k2", "v2")) .build(); Assertions.assertEquals(newId("k1", "v1", "k2", "v2"), id); } @Test public void iterableTags() { Id id = new Builder() .withTags(newId("k1", "v1", "k2", "v2").tags()) .build(); Assertions.assertEquals(newId("k1", "v1", "k2", "v2"), id); } @Test public void mapTags() { Map<String, String> tags = new HashMap<>(); tags.put("k1", "v1"); tags.put("k2", "v2"); Id id = new Builder() .withTags(tags) .build(); Assertions.assertEquals(newId("k1", "v1", "k2", "v2"), id); } @Test public void overwrite() { Id id = new Builder() .withTag("k", "v1") .withTag("k", "v2") .build(); Assertions.assertEquals(newId("k", "v1", "k", "v2"), id); } }
5,716
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/patterns/ThreadPoolMonitorTest.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api.patterns; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Gauge; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Measurement; import com.netflix.spectator.api.Meter; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Tag; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Iterator; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; public class ThreadPoolMonitorTest { private static final String THREAD_POOL_NAME = ThreadPoolMonitorTest.class.getSimpleName(); private Registry registry; private LatchedThreadPoolExecutor latchedExecutor; private static class TestRunnable implements Runnable { private final CountDownLatch synchronizer; private final CountDownLatch terminator; TestRunnable(final CountDownLatch synchronizer, final CountDownLatch terminator) { this.synchronizer = synchronizer; this.terminator = terminator; } @Override public void run() { try { synchronizer.countDown(); terminator.await(6, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } private static class LatchedThreadPoolExecutor extends ThreadPoolExecutor { private final AtomicInteger queueSize = new AtomicInteger(); private final AtomicInteger active = new AtomicInteger(); private final AtomicLong tasks = new AtomicLong(); private final AtomicLong completedTasks = new AtomicLong(); private volatile CountDownLatch completed; LatchedThreadPoolExecutor(final CountDownLatch completed) { super(3, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); this.completed = completed; } CountDownLatch getCompletedLatch() { return this.completed; } void setCompletedLatch(final CountDownLatch completedLatch) { this.completed = completedLatch; } @Override public void execute(Runnable task) { queueSize.incrementAndGet(); super.execute(task); } @Override protected void beforeExecute(Thread t, Runnable r) { queueSize.decrementAndGet(); active.incrementAndGet(); tasks.incrementAndGet(); super.beforeExecute(t, r); } @Override protected void afterExecute(Runnable r, Throwable t) { active.decrementAndGet(); completedTasks.incrementAndGet(); completed.countDown(); super.afterExecute(r, t); } @Override public int getActiveCount() { return active.get(); } @Override public long getTaskCount() { return tasks.get(); } @Override public long getCompletedTaskCount() { return completedTasks.get(); } @Override public BlockingQueue<Runnable> getQueue() { return new LinkedBlockingQueue<Runnable>() { @Override public int size() { return queueSize.get(); } }; } } @BeforeEach public void setUp() throws Exception { registry = new DefaultRegistry(); latchedExecutor = new LatchedThreadPoolExecutor(new CountDownLatch(1)); } @AfterEach public void tearDown() throws Exception { registry = null; latchedExecutor.shutdown(); latchedExecutor = null; } @Test public void monitorThrowsIfNullRegistry() throws Exception { Assertions.assertThrows(NullPointerException.class, () -> ThreadPoolMonitor.attach(null, latchedExecutor, THREAD_POOL_NAME)); } @Test public void monitorThrowsIfNullThreadPool() throws Exception { Assertions.assertThrows(NullPointerException.class, () -> ThreadPoolMonitor.attach(registry, null, THREAD_POOL_NAME)); } @Test public void monitorAcceptsNullThreadPoolName() { ThreadPoolMonitor.attach(registry, latchedExecutor, null); } private Meter getMeter(String meterName, String threadPoolName) { ThreadPoolMonitor.attach(registry, latchedExecutor, threadPoolName); PolledMeter.update(registry); final Id id = registry.createId(meterName).withTag(ThreadPoolMonitor.ID_TAG_NAME, (threadPoolName == null || threadPoolName.isEmpty()) ? ThreadPoolMonitor.DEFAULT_ID : threadPoolName); return registry.get(id); } private Meter getMeter(String meterName) { return getMeter(meterName, THREAD_POOL_NAME); } private Gauge getGauge(String meterName) { return (Gauge) getMeter(meterName, THREAD_POOL_NAME); } private Counter getCounter(String meterName) { return (Counter) getMeter(meterName, THREAD_POOL_NAME); } @Test public void metricsAreTaggedWithProvidedThreadPoolName() { checkIdTagValue(getMeter(ThreadPoolMonitor.MAX_THREADS), getClass().getSimpleName()); } @Test public void metricsAreTaggedWithDefaultThreadPoolNameIfNull() { checkIdTagValue(getMeter(ThreadPoolMonitor.MAX_THREADS, null), ThreadPoolMonitor.DEFAULT_ID); } @Test public void metricsAreTaggedWithDefaultThreadPoolNameIfEmpty() { checkIdTagValue(getMeter(ThreadPoolMonitor.MAX_THREADS, ""), ThreadPoolMonitor.DEFAULT_ID); } private void checkIdTagValue(Meter meter, String expectedIdValue) { final Iterable<Measurement> measurements = meter.measure(); final Iterator<Measurement> measurementIterator = measurements.iterator(); Assertions.assertTrue(measurementIterator.hasNext()); final Iterator<Tag> tags = measurementIterator.next().id().tags().iterator(); Assertions.assertTrue(tags.hasNext()); Tag tag = tags.next(); Assertions.assertEquals(ThreadPoolMonitor.ID_TAG_NAME, tag.key()); Assertions.assertEquals(expectedIdValue, tag.value()); } @Test public void threadPoolMonitorHasTaskCountMeter() { Assertions.assertNotNull(getMeter(ThreadPoolMonitor.TASK_COUNT)); } @Test public void threadPoolMonitorHasCompletedTaskCountMeter() { Assertions.assertNotNull(getMeter(ThreadPoolMonitor.COMPLETED_TASK_COUNT)); } @Test public void threadPoolMonitorHasCurrentThreadsBusyMeter() { Assertions.assertNotNull(getMeter(ThreadPoolMonitor.CURRENT_THREADS_BUSY)); } @Test public void threadPoolMonitorHasMaxThreadsMeter() { Assertions.assertNotNull(getMeter(ThreadPoolMonitor.MAX_THREADS)); } @Test public void threadPoolMonitorHasPoolSizeMeter() { Assertions.assertNotNull(getMeter(ThreadPoolMonitor.POOL_SIZE)); } @Test public void threadPoolMonitorHasCorePoolSizeMeter() { Assertions.assertNotNull(getMeter(ThreadPoolMonitor.CORE_POOL_SIZE)); } @Test public void threadPoolMonitorHasQueueSizeMeter() { Assertions.assertNotNull(getMeter(ThreadPoolMonitor.QUEUE_SIZE)); } @Test public void threadPoolMonitorHasRejectedExecutionsCounter() { ThreadPoolMonitor.attach(registry, latchedExecutor, THREAD_POOL_NAME); latchedExecutor.shutdown(); int rejected = 0; try { latchedExecutor.submit(() -> {}); } catch (RejectedExecutionException e) { e.printStackTrace(); ++rejected; } Counter c = registry.counter(ThreadPoolMonitor.REJECTED_TASK_COUNT, "id", THREAD_POOL_NAME); Assertions.assertNotNull(c); Assertions.assertEquals(rejected, c.count()); } @Test public void maxThreadsUpdatesWhenRegistryIsUpdated() { final Gauge gauge = getGauge(ThreadPoolMonitor.MAX_THREADS); Assertions.assertEquals(10.0, gauge.value(), 1e-12); latchedExecutor.setMaximumPoolSize(42); PolledMeter.update(registry); Assertions.assertEquals(42.0, gauge.value(), 1e-12); } @Test public void corePoolSizeUpdatesWhenRegistryIsUpdated() { final Gauge gauge = getGauge(ThreadPoolMonitor.CORE_POOL_SIZE); Assertions.assertEquals(3.0, gauge.value(), 1e-12); // Must be <= 10 because that is the max pool size used in the test. Starting with // jdk9 the it will validate and fail if trying to set the pool size larger than // the max latchedExecutor.setCorePoolSize(7); PolledMeter.update(registry); Assertions.assertEquals(7.0, gauge.value(), 1e-12); } @Test public void taskCountUpdates() throws InterruptedException { final Counter counter = getCounter(ThreadPoolMonitor.TASK_COUNT); Assertions.assertEquals(0, counter.count()); final CountDownLatch synchronizer = new CountDownLatch(1); final CountDownLatch terminator = new CountDownLatch(1); final TestRunnable command = new TestRunnable(synchronizer, terminator); latchedExecutor.execute(command); synchronizer.await(6, TimeUnit.SECONDS); PolledMeter.update(registry); Assertions.assertEquals(1, counter.count(), 1e-12); terminator.countDown(); } @Test public void currentThreadsBusyCountUpdates() throws InterruptedException { final Gauge gauge = getGauge(ThreadPoolMonitor.CURRENT_THREADS_BUSY); Assertions.assertEquals(0.0, gauge.value(), 1e-12); final CountDownLatch synchronizer = new CountDownLatch(1); final CountDownLatch terminator = new CountDownLatch(1); final TestRunnable command = new TestRunnable(synchronizer, terminator); latchedExecutor.execute(command); synchronizer.await(6, TimeUnit.SECONDS); PolledMeter.update(registry); Assertions.assertEquals(1.0, gauge.value(), 1e-12); terminator.countDown(); latchedExecutor.getCompletedLatch().await(6, TimeUnit.SECONDS); PolledMeter.update(registry); Assertions.assertEquals(0.0, gauge.value(), 1e-12); } @Test public void completedTaskCountUpdates() throws InterruptedException { final Counter counter = getCounter(ThreadPoolMonitor.COMPLETED_TASK_COUNT); Assertions.assertEquals(0, counter.count()); final CountDownLatch synchronizer = new CountDownLatch(2); final CountDownLatch terminator1 = new CountDownLatch(1); final CountDownLatch terminator2 = new CountDownLatch(1); final TestRunnable command1 = new TestRunnable(synchronizer, terminator1); final TestRunnable command2 = new TestRunnable(synchronizer, terminator2); latchedExecutor.execute(command1); latchedExecutor.execute(command2); synchronizer.await(6, TimeUnit.SECONDS); PolledMeter.update(registry); Assertions.assertEquals(0, counter.count()); terminator1.countDown(); latchedExecutor.getCompletedLatch().await(6, TimeUnit.SECONDS); PolledMeter.update(registry); Assertions.assertEquals(1, counter.count(), 1e-12); latchedExecutor.setCompletedLatch(new CountDownLatch(1)); terminator2.countDown(); latchedExecutor.getCompletedLatch().await(6, TimeUnit.SECONDS); PolledMeter.update(registry); Assertions.assertEquals(2, counter.count()); } @Test public void poolSizeUpdates() throws InterruptedException { final Gauge gauge = getGauge(ThreadPoolMonitor.POOL_SIZE); Assertions.assertEquals(0.0, gauge.value(), 1e-12); final CountDownLatch synchronizer = new CountDownLatch(2); final CountDownLatch terminator1 = new CountDownLatch(1); final CountDownLatch terminator2 = new CountDownLatch(1); final TestRunnable command1 = new TestRunnable(synchronizer, terminator1); final TestRunnable command2 = new TestRunnable(synchronizer, terminator2); latchedExecutor.execute(command1); latchedExecutor.execute(command2); synchronizer.await(6, TimeUnit.SECONDS); PolledMeter.update(registry); Assertions.assertEquals(2.0, gauge.value(), 1e-12); terminator1.countDown(); terminator2.countDown(); } @Test public void queueSizeUpdates() throws InterruptedException { latchedExecutor.setCorePoolSize(1); latchedExecutor.setMaximumPoolSize(1); final Gauge gauge = getGauge(ThreadPoolMonitor.QUEUE_SIZE); Assertions.assertEquals(0.0, gauge.value(), 1e-12); final CountDownLatch synchronizer1 = new CountDownLatch(1); final CountDownLatch synchronizer2 = new CountDownLatch(1); final CountDownLatch terminator123 = new CountDownLatch(1); final CountDownLatch terminator2 = new CountDownLatch(1); final TestRunnable command1 = new TestRunnable(synchronizer1, terminator123); final TestRunnable command2 = new TestRunnable(synchronizer1, terminator123); final TestRunnable command3 = new TestRunnable(synchronizer1, terminator123); final TestRunnable command4 = new TestRunnable(synchronizer2, terminator2); final TestRunnable command5 = new TestRunnable(synchronizer2, terminator2); final TestRunnable command6 = new TestRunnable(synchronizer2, terminator2); final TestRunnable command7 = new TestRunnable(synchronizer2, terminator2); latchedExecutor.execute(command1); latchedExecutor.execute(command2); latchedExecutor.execute(command3); latchedExecutor.execute(command4); latchedExecutor.execute(command5); latchedExecutor.execute(command6); latchedExecutor.execute(command7); synchronizer1.await(6, TimeUnit.SECONDS); PolledMeter.update(registry); Assertions.assertEquals(6.0, gauge.value(), 1e-12); latchedExecutor.setCompletedLatch(new CountDownLatch(3)); terminator123.countDown(); latchedExecutor.getCompletedLatch().await(6, TimeUnit.SECONDS); synchronizer2.await(6, TimeUnit.SECONDS); PolledMeter.update(registry); Assertions.assertEquals(3.0, gauge.value(), 1e-12); terminator2.countDown(); } }
5,717
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/patterns/IntervalCounterTest.java
/* * Copyright 2014-2019 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. */ package com.netflix.spectator.api.patterns; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.ManualClock; import com.netflix.spectator.api.Measurement; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Statistic; import com.netflix.spectator.api.Utils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; public class IntervalCounterTest { private final ManualClock clock = new ManualClock(); private static final double EPSILON = 1e-12; @BeforeEach public void before() { clock.setWallTime(0L); clock.setMonotonicTime(0L); } @Test public void testInit() { Registry r = new DefaultRegistry(clock); clock.setWallTime(42 * 1000L); Id id = r.createId("test"); IntervalCounter c = IntervalCounter.get(r, id); Assertions.assertEquals(0L, c.count()); Assertions.assertEquals(42.0, c.secondsSinceLastUpdate(), EPSILON); } @Test public void testInterval() { Registry r = new DefaultRegistry(clock); Id id = r.createId("test"); IntervalCounter c = IntervalCounter.get(r, id); Assertions.assertEquals(c.secondsSinceLastUpdate(), 0.0, EPSILON); clock.setWallTime(1000); Assertions.assertEquals(c.secondsSinceLastUpdate(), 1.0, EPSILON); c.increment(); Assertions.assertEquals(c.secondsSinceLastUpdate(), 0.0, EPSILON); } @Test public void testIncrement() { Registry r = new DefaultRegistry(clock); Id id = r.createId("test"); Counter c = IntervalCounter.get(r, id); Assertions.assertEquals(0, c.count()); c.increment(); Assertions.assertEquals(1, c.count()); c.increment(41); Assertions.assertEquals(42, c.count()); } private static List<Measurement> getAllMeasurements(Registry registry) { PolledMeter.update(registry); final List<Measurement> result = new ArrayList<>(); registry.stream() .filter(meter -> !meter.hasExpired()) .forEach(meter -> meter.measure().forEach(result::add)); return result; } @Test public void testMeasure() { Registry r = new DefaultRegistry(clock); clock.setWallTime(61000L); Id id = r.createId("test"); Counter c = IntervalCounter.get(r, id); // all meters should have the correct timestamp r.stream().forEach(meter -> { for (Measurement m : meter.measure()) { Assertions.assertEquals(m.timestamp(), 61000L); } }); final List<Measurement> measurements = getAllMeasurements(r); final double initAge = Utils.first(measurements, Statistic.duration).value(); final double initCount = Utils.first(measurements, Statistic.count).value(); Assertions.assertEquals(61.0, initAge, EPSILON); Assertions.assertEquals(0.0, initCount, EPSILON); clock.setWallTime(120000L); c.increment(); final List<Measurement> afterMeasurements = getAllMeasurements(r); final double afterAge = Utils.first(afterMeasurements, Statistic.duration).value(); final double afterCount = Utils.first(afterMeasurements, Statistic.count).value(); Assertions.assertEquals(0.0, afterAge, EPSILON); Assertions.assertEquals(1.0, afterCount, EPSILON); } @Test public void testReusesInstance() { Registry r = new DefaultRegistry(clock); Id id = r.createId("test"); Counter c1 = IntervalCounter.get(r, id); Counter c2 = IntervalCounter.get(r, id); Assertions.assertSame(c1, c2); } }
5,718
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/patterns/LongTaskTimerTest.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api.patterns; import com.netflix.spectator.api.*; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class LongTaskTimerTest { private final ManualClock clock = new ManualClock(); private final Registry registry = new DefaultRegistry(clock); private final Id id = registry.createId("test"); @Test public void testInit() { com.netflix.spectator.api.LongTaskTimer t = LongTaskTimer.get(registry, id); Assertions.assertEquals(t.duration(), 0L); Assertions.assertEquals(t.activeTasks(), 0L); } @Test public void testStart() { com.netflix.spectator.api.LongTaskTimer t = LongTaskTimer.get(registry, id); long task1 = t.start(); long task2 = t.start(); Assertions.assertNotEquals(task1, task2); Assertions.assertEquals(t.activeTasks(), 2); Assertions.assertEquals(t.duration(), 0L); } @Test public void testStop() { com.netflix.spectator.api.LongTaskTimer t = LongTaskTimer.get(registry, id); long task1 = t.start(); long task2 = t.start(); Assertions.assertEquals(t.activeTasks(), 2); clock.setMonotonicTime(5L); Assertions.assertEquals(t.duration(), 10L); long elapsed1 = t.stop(task1); Assertions.assertEquals(-1L, t.stop(task1)); // second call to stop should return an error Assertions.assertEquals(elapsed1, 5L); Assertions.assertEquals(t.duration(task2), 5L); Assertions.assertEquals(t.duration(task1), -1L); // task is gone, should return default Assertions.assertEquals(t.duration(), 5L); } @Test public void stateIsPreservedAcrossGets() { long t1 = LongTaskTimer.get(registry, id).start(); long t2 = LongTaskTimer.get(registry, id).start(); Assertions.assertNotEquals(t1, t2); Assertions.assertEquals(LongTaskTimer.get(registry, id).activeTasks(), 2); clock.setMonotonicTime(5L); Assertions.assertEquals(LongTaskTimer.get(registry, id).duration(), 10L); LongTaskTimer.get(registry, id).stop(t1); Assertions.assertEquals(LongTaskTimer.get(registry, id).duration(), 5L); } private void assertLongTaskTimer(Meter t, long timestamp, int activeTasks, double duration) { for (Measurement m : t.measure()) { Assertions.assertEquals(m.timestamp(), timestamp); if (m.id().equals(t.id().withTag(Statistic.activeTasks))) { Assertions.assertEquals(m.value(), activeTasks, 1.0e-12); } else if (m.id().equals(t.id().withTag(Statistic.duration))) { Assertions.assertEquals(m.value(), duration, 1.0e-12); } else { Assertions.fail("unexpected id: " + m.id()); } } } @Test public void testMeasure() { com.netflix.spectator.api.LongTaskTimer t = LongTaskTimer.get(registry, id); long task1 = t.start(); clock.setMonotonicTime(1_000_000_000L); clock.setWallTime(1L); assertLongTaskTimer(t, 1L, 1, 1.0); long task2 = t.start(); assertLongTaskTimer(t, 1L, 2, 1.0); t.stop(task1); assertLongTaskTimer(t, 1L, 1, 0.0); t.stop(task2); assertLongTaskTimer(t, 1L, 0, 0.0); } // https://github.com/Netflix/spectator/issues/503 @Test public void usingNoopRegistry() { System.setProperty("spectator.api.propagateWarnings", "true"); Registry noop = new NoopRegistry(); LongTaskTimer.get(noop, noop.createId("task")); } }
5,719
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/patterns/CardinalityLimitersTest.java
/* * Copyright 2014-2019 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. */ package com.netflix.spectator.api.patterns; import com.netflix.spectator.api.ManualClock; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Set; import java.util.TreeSet; import java.util.function.Function; public class CardinalityLimitersTest { @Test public void first2() { Function<String, String> f = CardinalityLimiters.first(2); Assertions.assertEquals("a", f.apply("a")); Assertions.assertEquals("b", f.apply("b")); Assertions.assertEquals(CardinalityLimiters.OTHERS, f.apply("c")); Assertions.assertEquals("a", f.apply("a")); } @Test public void firstToStringEmpty() { Function<String, String> f = CardinalityLimiters.first(2); Assertions.assertEquals("FirstLimiter()", f.toString()); } @Test public void firstToStringPartial() { Function<String, String> f = CardinalityLimiters.first(2); Assertions.assertEquals("b", f.apply("b")); Assertions.assertEquals("FirstLimiter(b)", f.toString()); } @Test public void firstToStringFull() { Function<String, String> f = CardinalityLimiters.first(2); Assertions.assertEquals("a", f.apply("a")); Assertions.assertEquals("b", f.apply("b")); Assertions.assertEquals("FirstLimiter(a,b)", f.toString()); } private void updateN(Function<String, String> f, int n, String s) { for (int i = 0; i < n; ++i) { f.apply(s); } } private void advanceClock(ManualClock clock) { long t = clock.wallTime(); clock.setWallTime(t + 10 * 60000 + 1); } @Test public void mostFrequentUnderLimit() { int n = 27; ManualClock clock = new ManualClock(0L, 0L); Function<String, String> f = CardinalityLimiters.mostFrequent(n, clock); for (int t = 0; t < 1000; ++t) { for (int i = 0; i < n; ++i) { Assertions.assertEquals("" + i, f.apply("" + i)); } clock.setWallTime(t * 1000); } } @Test public void mostFrequentIsUsed() { ManualClock clock = new ManualClock(0L, 0L); Function<String, String> f = CardinalityLimiters.mostFrequent(2, clock); // Setup some basic stats updateN(f, 4, "a"); updateN(f, 3, "b"); updateN(f, 2, "c"); updateN(f, 1, "d"); // Refresh cutoff, should be 3 for the top 2 advanceClock(clock); Assertions.assertEquals("a", f.apply("a")); // If the values are close then bias towards the names that come first alphabetically Assertions.assertEquals(CardinalityLimiters.OTHERS, f.apply("c")); Assertions.assertEquals("b", f.apply("b")); // Until the cutoff is updated, "d" won't show up no matter how frequent Assertions.assertEquals(CardinalityLimiters.OTHERS, f.apply("d")); updateN(f, 42, "d"); Assertions.assertEquals(CardinalityLimiters.OTHERS, f.apply("d")); // Now "d" is most frequent advanceClock(clock); Assertions.assertEquals("d", f.apply("d")); } @Test public void mostFrequentAllUnique() { // Ensure we have a somewhat stable set and there isn't a memory leak if every value is // unique. For example, if a user tried to use a request id. ManualClock clock = new ManualClock(0L, 0L); Function<String, String> f = CardinalityLimiters.mostFrequent(2, clock); Set<String> values = new TreeSet<>(); for (int i = 0; i < 10000; ++i) { values.add(f.apply("" + i)); clock.setWallTime(i * 1000); } // The values less than equal 9616 should have been cleaned up based on the clock Assertions.assertFalse(f.toString().contains("9616")); Assertions.assertEquals(3, values.size()); } @Test public void mostFrequentTransitionTime() { // Ensure we have a somewhat stable set and there isn't a memory leak if every value is // unique. For example, if a user tried to use a request id. ManualClock clock = new ManualClock(0L, 0L); Function<String, String> f = CardinalityLimiters.mostFrequent(2, clock); Set<String> values = new TreeSet<>(); // Lots of activity on old asg long i = 0; for (; i < 1_000_000; ++i) { values.add(f.apply("app-a-v001")); values.add(f.apply("app-b-v001")); clock.setWallTime(i * 1000); } // Activity moved to new asg for (; i < 2_000_000; ++i) { values.add(f.apply("app-a-v002")); values.add(f.apply("app-b-v001")); clock.setWallTime(i * 1000); } Assertions.assertTrue(values.contains("app-a-v002")); } @Test public void mostFrequentTemporaryChurn() { ManualClock clock = new ManualClock(0L, 0L); Function<String, String> f = CardinalityLimiters.mostFrequent(2, clock); Set<String> values = new TreeSet<>(); for (int t = 0; t < 250; ++t) { if (t < 100) { values.add(f.apply("a")); } else if (t < 117) { // Simulates 17 minutes of high churn for (int i = 0; i < 200; ++i) { values.add(f.apply("" + i)); } } else { // This should come through within 2h values.add(f.apply("b")); } clock.setWallTime(t * 60000); } Assertions.assertEquals(6, values.size()); Assertions.assertEquals("b", f.apply("b")); } @Test public void mostFrequentClusterUniform() { // Simulate a cluster with independent limiters where high cardinality values are // coming in round-robin to each node of the cluster. int warmupEnd = 60; int finalEnd = 24 * 60; int cardinalityLimit = 25; int clusterSize = 18; int numValues = 2000; // Ensure we have a somewhat stable set and there isn't a memory leak if every value is // unique. For example, if a user tried to use a request id. ManualClock clock = new ManualClock(0L, 0L); List<Function<String, String>> limiters = new ArrayList<>(); for (int i = 0; i < clusterSize; ++i) { limiters.add(CardinalityLimiters.mostFrequent(cardinalityLimit, clock)); } Random r = new Random(42); Set<String> values = new TreeSet<>(); Runnable singleIteration = () -> { for (int v = 0; v < numValues; ++v) { int n = r.nextInt(limiters.size()); Function<String, String> f = limiters.get(n); values.add(f.apply("" + v)); } }; int t = 0; for (; t < warmupEnd; ++t) { singleIteration.run(); clock.setWallTime(t * 60000); } // Should be proportional to the cluster size, not the number of input values Assertions.assertTrue(values.size() < 2 * clusterSize * cardinalityLimit); values.clear(); for (; t < finalEnd; ++t) { singleIteration.run(); clock.setWallTime(t * 60000); } // Should only have the others value Assertions.assertEquals(1, values.size()); } @Test public void mostFrequentClusterBiased() { // Simulate a cluster with independent limiters where high cardinality values are // coming in round-robin to each node of the cluster. There is a small set of more // frequent values that should be preserved. int warmupEnd = 12 * 60; int finalEnd = 24 * 60; int cardinalityLimit = 25; int clusterSize = 18; int numFrequentValues = 10; int numValues = 2000; // Setup a separate limiter for each node of the cluster ManualClock clock = new ManualClock(0L, 0L); List<Function<String, String>> limiters = new ArrayList<>(); for (int i = 0; i < clusterSize; ++i) { limiters.add(CardinalityLimiters.mostFrequent(cardinalityLimit, clock)); } Random r = new Random(42); Set<String> values = new TreeSet<>(); Runnable singleIteration = () -> { // Values with heavier use for (int v = 0; v < numFrequentValues; ++v) { for (int i = 0; i < 1 + v; ++i) { int n = r.nextInt(limiters.size()); Function<String, String> f = limiters.get(n); values.add(f.apply("" + v)); } } // Big tail of values with a lot of churn for (int v = 0; v < numValues; ++v) { int n = r.nextInt(limiters.size()); Function<String, String> f = limiters.get(n); values.add(f.apply("" + v)); } }; // Warmup phase, there will be a bit of a burst here, but it should stabilize quickly // and start eliminating values with high amounts of churn int t = 0; for (; t < warmupEnd; ++t) { singleIteration.run(); clock.setWallTime(t * 60000); } // Should be proportional to the cluster size, not the number of input values Assertions.assertTrue(values.size() < 2 * clusterSize * cardinalityLimit); // Stable phase, general trend is established and only higher frequency values should // be reported with agreement for the most part across nodes values.clear(); for (; t < finalEnd; ++t) { singleIteration.run(); clock.setWallTime(t * 60000); } // It should have started converging on the frequent set and dropping the values with // too much churn even though this restricts it below the specified limit. Assertions.assertTrue(values.size() < 2 * numFrequentValues); } @Test public void rollupNegative() { Function<String, String> f = CardinalityLimiters.rollup(-2); Assertions.assertEquals(CardinalityLimiters.AUTO_ROLLUP, f.apply("a")); Assertions.assertEquals(CardinalityLimiters.AUTO_ROLLUP, f.apply("b")); } @Test public void rollupZero() { Function<String, String> f = CardinalityLimiters.rollup(0); Assertions.assertEquals(CardinalityLimiters.AUTO_ROLLUP, f.apply("a")); Assertions.assertEquals(CardinalityLimiters.AUTO_ROLLUP, f.apply("b")); } @Test public void rollup2() { Function<String, String> f = CardinalityLimiters.rollup(2); Assertions.assertEquals("a", f.apply("a")); Assertions.assertEquals("b", f.apply("b")); Assertions.assertEquals(CardinalityLimiters.AUTO_ROLLUP, f.apply("c")); Assertions.assertEquals(CardinalityLimiters.AUTO_ROLLUP, f.apply("a")); } @Test public void registeredNameOrIp() { Function<String, String> registeredNamelimiter = CardinalityLimiters.first(2); Function<String, String> ipNamelimiter = CardinalityLimiters.first(2); Function<String, String> limiter = CardinalityLimiters.registeredNameOrIp(registeredNamelimiter, ipNamelimiter); //Allow two IPs Assertions.assertEquals("127.0.0.1", limiter.apply("127.0.0.1")); Assertions.assertEquals("[::1]", limiter.apply("[::1]")); //Further IPs are limited Assertions.assertEquals(CardinalityLimiters.OTHERS, limiter.apply("127.0.0.2")); Assertions.assertEquals(CardinalityLimiters.OTHERS, limiter.apply("[::2]")); Assertions.assertEquals(CardinalityLimiters.OTHERS, limiter.apply("[v1.::1]")); Assertions.assertEquals(CardinalityLimiters.OTHERS, limiter.apply("[::1%0]")); //Allow two registry names Assertions.assertEquals("example.com", limiter.apply("example.com")); Assertions.assertEquals("spectator", limiter.apply("spectator")); //Further registry names are rolled up Assertions.assertEquals(CardinalityLimiters.OTHERS, limiter.apply("subdomain.example.com")); //Original IP are still allowed Assertions.assertEquals("127.0.0.1", limiter.apply("127.0.0.1")); Assertions.assertEquals("[::1]", limiter.apply("[::1]")); } @Test public void registeredNameOrIpAnchorsIps() { Function<String, String> registeredNamelimiter = CardinalityLimiters.first(4); Function<String, String> ipNamelimiter = CardinalityLimiters.first(0); Function<String, String> limiter = CardinalityLimiters.registeredNameOrIp(Function.identity(), s -> CardinalityLimiters.OTHERS); //Confirm test setup that IPs limited Assertions.assertEquals(CardinalityLimiters.OTHERS, limiter.apply("127.0.0.1")); //IP-like registered names are allowed Assertions.assertEquals("127.0.0.1.example.com", limiter.apply("127.0.0.1.example.com")); Assertions.assertEquals("vip-127.0.0.1", limiter.apply("vip-127.0.0.1")); Assertions.assertEquals("[::1]-vip", limiter.apply("[::1]-vip")); Assertions.assertEquals("vip-[::1]", limiter.apply("vip-[::1]")); } @SuppressWarnings("unchecked") static void checkSerde(Function<String, String> limiter) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (ObjectOutputStream out = new ObjectOutputStream(baos)) { out.writeObject(limiter); } ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); try (ObjectInputStream in = new ObjectInputStream(bais)) { Function<String, String> deserialized = (Function<String, String>) in.readObject(); Assertions.assertEquals(limiter.toString(), deserialized.toString()); } } catch (Exception e) { throw new RuntimeException(e); } } @Test public void firstSerializability() { Function<String, String> limiter = CardinalityLimiters.first(2); limiter.apply("a"); limiter.apply("b"); limiter.apply("c"); checkSerde(limiter); } @Test public void mostFrequentSerializability() { Function<String, String> limiter = CardinalityLimiters.mostFrequent(2); limiter.apply("a"); limiter.apply("b"); limiter.apply("c"); checkSerde(limiter); } @Test public void rollupSerializability() { Function<String, String> limiter = CardinalityLimiters.rollup(2); limiter.apply("a"); limiter.apply("b"); limiter.apply("c"); checkSerde(limiter); } @Test public void registeredNameOrIpSerializability() { Function<String, String> registeredNamelimiter = CardinalityLimiters.first(5); Function<String, String> ipNamelimiter = CardinalityLimiters.first(2); Function<String, String> limiter = CardinalityLimiters.registeredNameOrIp(registeredNamelimiter, ipNamelimiter); limiter.apply("127.0.0.1"); limiter.apply("[::1]"); limiter.apply("example.com"); checkSerde(limiter); } }
5,720
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/patterns/MonotonicCounterTest.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api.patterns; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.ManualClock; import com.netflix.spectator.api.Registry; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.lang.ref.WeakReference; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.LongAdder; public class MonotonicCounterTest { private final ManualClock clock = new ManualClock(); private final Registry registry = new DefaultRegistry(clock); private final Id id = registry.createId("test"); private void update() { PolledMeter.update(registry); } @Test public void usingAtomicLong() { AtomicLong count = new AtomicLong(); AtomicLong c = PolledMeter.using(registry).withId(id).monitorMonotonicCounter(count); Assertions.assertSame(count, c); Counter counter = registry.counter(id); update(); Assertions.assertEquals(0L, counter.count()); c.incrementAndGet(); update(); Assertions.assertEquals(1L, counter.count()); c.addAndGet(42); update(); Assertions.assertEquals(43L, counter.count()); } @Test public void usingLongAdder() { LongAdder count = new LongAdder(); LongAdder c = PolledMeter.using(registry).withId(id).monitorMonotonicCounter(count); Assertions.assertSame(count, c); Counter counter = registry.counter(id); update(); Assertions.assertEquals(0L, counter.count()); c.increment(); update(); Assertions.assertEquals(1L, counter.count()); c.add(42); update(); Assertions.assertEquals(43L, counter.count()); } @Test public void nonMonotonicUpdates() { AtomicLong count = new AtomicLong(); AtomicLong c = PolledMeter.using(registry).withId(id).monitorMonotonicCounter(count); Counter counter = registry.counter(id); update(); Assertions.assertEquals(0L, counter.count()); c.set(42L); update(); Assertions.assertEquals(42L, counter.count()); // Should not update the counter because it is lower, but must update // the previous recorded value c.set(21L); update(); Assertions.assertEquals(42L, counter.count()); // Make sure a subsequent increase is detected c.set(23L); update(); Assertions.assertEquals(44L, counter.count()); } @Test public void expire() throws Exception { WeakReference<LongAdder> ref = new WeakReference<>( PolledMeter.using(registry).withId(id).monitorMonotonicCounter(new LongAdder())); while (ref.get() != null) { System.gc(); } Assertions.assertEquals(1, registry.state().size()); update(); Assertions.assertEquals(0, registry.state().size()); } @Test public void removeGauge() throws Exception { LongAdder v = PolledMeter.using(registry).withId(id).monitorMonotonicCounter(new LongAdder()); Assertions.assertEquals(1, registry.state().size()); PolledMeter.remove(registry, id); Assertions.assertEquals(0, registry.state().size()); } @Test public void removeOtherType() throws Exception { LongTaskTimer t = LongTaskTimer.get(registry, id); Assertions.assertEquals(3, registry.state().size()); PolledMeter.remove(registry, id); Assertions.assertEquals(3, registry.state().size()); } }
5,721
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/patterns/PolledMeterTest.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api.patterns; import com.netflix.spectator.api.Clock; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Gauge; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.RegistryConfig; import com.netflix.spectator.impl.AtomicDouble; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.LongAdder; public class PolledMeterTest { private static final AtomicLong COUNTER = new AtomicLong(); private static long testCounter() { return COUNTER.getAndIncrement(); } private static double testValue() { return 42.0; } @Test public void monitorStaticMethodValue() { Registry r = new DefaultRegistry(); Id id = r.createId("test"); PolledMeter.using(r).withId(id).monitorStaticMethodValue(PolledMeterTest::testValue); PolledMeter.update(r); Assertions.assertEquals(42.0, r.gauge(id).value()); } @Test public void monitorStaticMethodMonotonicCounter() { Registry r = new DefaultRegistry(); Id id = r.createId("test"); PolledMeter.using(r) .withId(id) .monitorStaticMethodMonotonicCounter(PolledMeterTest::testCounter); PolledMeter.update(r); PolledMeter.update(r); PolledMeter.update(r); PolledMeter.update(r); Assertions.assertEquals(4, r.counter(id).count()); } @Test public void monitorValueNull() { Registry r = new DefaultRegistry(Clock.SYSTEM, p -> null); Id id = r.createId("test"); PolledMeter.using(r).withId(id).<Collection<?>>monitorValue(null, Collection::size); PolledMeter.update(r); Assertions.assertEquals(Double.NaN, r.gauge(id).value()); } @Test public void monitorValueNullPropagate() { RegistryConfig config = s -> s.equals("propagateWarnings") ? "true" : null; Registry r = new DefaultRegistry(Clock.SYSTEM, config); Id id = r.createId("test"); IllegalArgumentException e = Assertions.assertThrows( IllegalArgumentException.class, () -> PolledMeter.using(r) .withId(id) .<Collection<?>>monitorValue(null, Collection::size) ); Assertions.assertTrue(e.getMessage().startsWith("obj is null")); } @Test public void monitorMonotonicCounterNull() { Registry r = new DefaultRegistry(Clock.SYSTEM, p -> null); Id id = r.createId("test"); AtomicLong v = new AtomicLong(42); PolledMeter.using(r).withId(id).<AtomicLong>monitorMonotonicCounter(null, n -> v.get()); PolledMeter.update(r); Assertions.assertEquals(0, r.counter(id).count()); } @Test public void monitorMonotonicCounterNullPropagate() { RegistryConfig config = s -> s.equals("propagateWarnings") ? "true" : null; Registry r = new DefaultRegistry(Clock.SYSTEM, config); Id id = r.createId("test"); AtomicLong v = new AtomicLong(42); IllegalArgumentException e = Assertions.assertThrows( IllegalArgumentException.class, () -> PolledMeter.using(r) .withId(id) .<AtomicLong>monitorValue(null, n -> v.get()) ); Assertions.assertTrue(e.getMessage().startsWith("obj is null")); } @Test public void monitorMonotonicCounterDouble() { Registry r = new DefaultRegistry(Clock.SYSTEM, p -> null); Id id = r.createId("test"); AtomicDouble v = PolledMeter.using(r) .withName("test") .monitorMonotonicCounterDouble(new AtomicDouble(), AtomicDouble::doubleValue); Assertions.assertEquals(0.0, r.counter(id).actualCount()); v.set(42.5); PolledMeter.update(r); Assertions.assertEquals(42.5, r.counter(id).actualCount()); // No change, value unexpectedly decreased v.set(1.0); PolledMeter.update(r); Assertions.assertEquals(42.5, r.counter(id).actualCount()); v.set(5.0); PolledMeter.update(r); Assertions.assertEquals(46.5, r.counter(id).actualCount()); } @Test public void removeAndAddRepeatedlyCounter() { Registry r = new DefaultRegistry(); Id id = r.createId("test"); AtomicLong value = new AtomicLong(); for (int i = 0; i < 10; ++i) { PolledMeter.using(r).withId(id).monitorMonotonicCounter(value); PolledMeter.update(r); value.incrementAndGet(); PolledMeter.update(r); PolledMeter.remove(r, id); } Assertions.assertEquals(10, r.counter("test").count()); } @Test public void removeAndAddRepeatedlyGauge() { Registry r = new DefaultRegistry(); Id id = r.createId("test"); AtomicLong value = new AtomicLong(); for (int i = 0; i < 10; ++i) { PolledMeter.using(r).withId(id).monitorValue(value); value.set(i); PolledMeter.update(r); PolledMeter.remove(r, id); } Assertions.assertEquals(9.0, r.gauge("test").value(), 1e-12); } @Test public void poll() { Registry r = new DefaultRegistry(); Gauge g = r.gauge("g"); Counter c = r.counter("c"); Assertions.assertTrue(Double.isNaN(g.value())); Assertions.assertEquals(0, c.count()); ScheduledFuture<?> future = PolledMeter.poll(r, () -> { g.set(1.0); c.increment(); }); future.cancel(true); Assertions.assertEquals(1.0, g.value(), 1e-12); Assertions.assertEquals(1, c.count()); } @Test public void monitorValueLongAdder() { final Registry r = new DefaultRegistry(Clock.SYSTEM, p -> null); final Id id = r.createId("test"); final LongAdder v = PolledMeter.using(r) .withName("test") .monitorValue(new LongAdder()); v.increment(); PolledMeter.update(r); Assertions.assertEquals(1.0, r.gauge(id).value()); v.decrement(); PolledMeter.update(r); Assertions.assertEquals(0.0, r.gauge(id).value()); v.add(50); PolledMeter.update(r); Assertions.assertEquals(50.0, r.gauge(id).value()); } @Test public void monitorSizeOfList() { final Registry r = new DefaultRegistry(Clock.SYSTEM, p -> null); final Id id = r.createId("test"); final List<String> list = PolledMeter.using(r) .withName("test") .monitorSize(Collections.synchronizedList(new ArrayList<String>())); list.add("a"); PolledMeter.update(r); Assertions.assertEquals(1.0, r.gauge(id).value()); list.add("b"); PolledMeter.update(r); Assertions.assertEquals(2.0, r.gauge(id).value()); list.clear(); PolledMeter.update(r); Assertions.assertEquals(0.0, r.gauge(id).value()); } @Test public void monitorSizeOfMap() { final Registry r = new DefaultRegistry(Clock.SYSTEM, p -> null); final Id id = r.createId("test"); final Map<String, String> map = PolledMeter.using(r) .withName("test") .monitorSize(new ConcurrentHashMap<String, String>()); map.put("a", "a-value"); PolledMeter.update(r); Assertions.assertEquals(1.0, r.gauge(id).value()); map.put("b", "b-value"); PolledMeter.update(r); Assertions.assertEquals(2.0, r.gauge(id).value()); map.remove("a"); map.remove("b"); PolledMeter.update(r); Assertions.assertEquals(0.0, r.gauge(id).value()); } }
5,722
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/histogram/PercentileBucketsTest.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api.histogram; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Random; public class PercentileBucketsTest { @Test public void indexOf() { Assertions.assertEquals(0, PercentileBuckets.indexOf(-1)); Assertions.assertEquals(0, PercentileBuckets.indexOf(0)); Assertions.assertEquals(1, PercentileBuckets.indexOf(1)); Assertions.assertEquals(2, PercentileBuckets.indexOf(2)); Assertions.assertEquals(3, PercentileBuckets.indexOf(3)); Assertions.assertEquals(4, PercentileBuckets.indexOf(4)); Assertions.assertEquals(25, PercentileBuckets.indexOf(87)); Assertions.assertEquals(PercentileBuckets.length() - 1, PercentileBuckets.indexOf(Long.MAX_VALUE)); } @Test public void indexOfSanityCheck() { Random r = new Random(42); for (int i = 0; i < 10000; ++i) { long v = r.nextLong(); if (v < 0) { Assertions.assertEquals(0, PercentileBuckets.indexOf(v)); } else { long b = PercentileBuckets.get(PercentileBuckets.indexOf(v)); Assertions.assertTrue(v <= b, String.format("%d > %d", v, b)); } } } @Test public void bucketSanityCheck() { Random r = new Random(42); for (int i = 0; i < 10000; ++i) { long v = r.nextLong(); if (v < 0) { Assertions.assertEquals(1, PercentileBuckets.bucket(v)); } else { long b = PercentileBuckets.bucket(v); Assertions.assertTrue(v <= b, String.format("%d > %d", v, b)); } } } @Test public void asArray() { long[] values = PercentileBuckets.asArray(); Assertions.assertEquals(PercentileBuckets.length(), values.length); for (int i = 0; i < values.length; ++i) { Assertions.assertEquals(PercentileBuckets.get(i), values[i]); } } @Test public void asArrayIsCopy() { long[] values = PercentileBuckets.asArray(); values[0] = 42; Assertions.assertEquals(1, PercentileBuckets.get(0)); } @Test public void map() { String[] values = PercentileBuckets.map(String.class, v -> String.format("%016X", v)); Assertions.assertEquals(PercentileBuckets.length(), values.length); for (int i = 0; i < values.length; ++i) { Assertions.assertEquals(PercentileBuckets.get(i), Long.parseLong(values[i], 16)); } } @Test public void percentiles() { long[] counts = new long[PercentileBuckets.length()]; for (int i = 0; i < 100_000; ++i) { ++counts[PercentileBuckets.indexOf(i)]; } double[] pcts = new double[] {0.0, 25.0, 50.0, 75.0, 90.0, 95.0, 98.0, 99.0, 99.5, 100.0}; double[] results = new double[pcts.length]; PercentileBuckets.percentiles(counts, pcts, results); double[] expected = new double[] {0.0, 25e3, 50e3, 75e3, 90e3, 95e3, 98e3, 99e3, 99.5e3, 100e3}; double threshold = 0.1 * 100_000; // quick check, should be within 10% of total Assertions.assertArrayEquals(expected, results, threshold); // Further check each value is within 10% of actual percentile for (int i = 0 ; i < results.length; ++i) { threshold = 0.1 * expected[i] + 1e-12; Assertions.assertEquals(expected[i], results[i], threshold); } } @Test public void percentile() { long[] counts = new long[PercentileBuckets.length()]; for (int i = 0; i < 100_000; ++i) { ++counts[PercentileBuckets.indexOf(i)]; } double[] pcts = new double[] {0.0, 25.0, 50.0, 75.0, 90.0, 95.0, 98.0, 99.0, 99.5, 100.0}; for (double pct : pcts) { double expected = pct * 1e3; double threshold = 0.1 * expected + 1e-12; Assertions.assertEquals(expected, PercentileBuckets.percentile(counts, pct), threshold); } } }
5,723
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/histogram/BucketTimerTest.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api.histogram; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Functions; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Timer; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; public class BucketTimerTest { private long sum(Registry r, String name) { return r.timers().filter(Functions.nameEquals(name)).mapToLong(Timer::count).sum(); } @Test public void basic() { Registry r = new DefaultRegistry(); BucketTimer t = BucketTimer.get( r, r.createId("test"), BucketFunctions.latency(4, TimeUnit.SECONDS)); t.record(3750, TimeUnit.MILLISECONDS); Assertions.assertEquals(1, r.timers().count()); Assertions.assertEquals(1, sum(r, "test")); t.record(4221, TimeUnit.MILLISECONDS); Assertions.assertEquals(2, r.timers().count()); Assertions.assertEquals(2, sum(r, "test")); t.record(4221, TimeUnit.MILLISECONDS); Assertions.assertEquals(2, r.timers().count()); Assertions.assertEquals(3, sum(r, "test")); } }
5,724
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/histogram/BucketCounterTest.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api.histogram; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Functions; import com.netflix.spectator.api.Registry; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; public class BucketCounterTest { private long sum(Registry r, String name) { return r.counters().filter(Functions.nameEquals(name)).mapToLong(Counter::count).sum(); } @Test public void basic() { Registry r = new DefaultRegistry(); BucketCounter c = BucketCounter.get( r, r.createId("test"), BucketFunctions.latency(4, TimeUnit.SECONDS)); c.record(TimeUnit.MILLISECONDS.toNanos(3750)); Assertions.assertEquals(1, r.counters().count()); Assertions.assertEquals(1, sum(r, "test")); c.record(TimeUnit.MILLISECONDS.toNanos(4221)); Assertions.assertEquals(2, r.counters().count()); Assertions.assertEquals(2, sum(r, "test")); c.record(TimeUnit.MILLISECONDS.toNanos(4221)); Assertions.assertEquals(2, r.counters().count()); Assertions.assertEquals(3, sum(r, "test")); } @Test public void increment() { Registry r = new DefaultRegistry(); BucketCounter c = BucketCounter.get( r, r.createId("test"), BucketFunctions.latency(4, TimeUnit.SECONDS)); c.record(TimeUnit.MILLISECONDS.toNanos(3750)); Assertions.assertEquals(1, r.counters().count()); Assertions.assertEquals(1, sum(r, "test")); c.increment(TimeUnit.MILLISECONDS.toNanos(3750), 5); Assertions.assertEquals(1, r.counters().count()); Assertions.assertEquals(6, sum(r, "test")); } }
5,725
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/histogram/BucketFunctionsTest.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api.histogram; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.HashSet; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.function.LongFunction; public class BucketFunctionsTest { @Test public void age60s() { LongFunction<String> f = BucketFunctions.age(60, TimeUnit.SECONDS); Assertions.assertEquals("future", f.apply(TimeUnit.SECONDS.toNanos(-1))); Assertions.assertEquals("07s", f.apply(TimeUnit.SECONDS.toNanos(0))); Assertions.assertEquals("07s", f.apply(TimeUnit.SECONDS.toNanos(1))); Assertions.assertEquals("07s", f.apply(TimeUnit.SECONDS.toNanos(6))); Assertions.assertEquals("07s", f.apply(TimeUnit.SECONDS.toNanos(7))); Assertions.assertEquals("15s", f.apply(TimeUnit.SECONDS.toNanos(8))); Assertions.assertEquals("15s", f.apply(TimeUnit.SECONDS.toNanos(10))); Assertions.assertEquals("30s", f.apply(TimeUnit.SECONDS.toNanos(20))); Assertions.assertEquals("30s", f.apply(TimeUnit.SECONDS.toNanos(30))); Assertions.assertEquals("60s", f.apply(TimeUnit.SECONDS.toNanos(31))); Assertions.assertEquals("60s", f.apply(TimeUnit.SECONDS.toNanos(42))); Assertions.assertEquals("60s", f.apply(TimeUnit.SECONDS.toNanos(60))); Assertions.assertEquals("old", f.apply(TimeUnit.SECONDS.toNanos(61))); } @Test public void age60sBiasOld() { LongFunction<String> f = BucketFunctions.ageBiasOld(60, TimeUnit.SECONDS); Assertions.assertEquals("future", f.apply(TimeUnit.SECONDS.toNanos(-1))); Assertions.assertEquals("30s", f.apply(TimeUnit.SECONDS.toNanos(0))); Assertions.assertEquals("30s", f.apply(TimeUnit.SECONDS.toNanos(1))); Assertions.assertEquals("30s", f.apply(TimeUnit.SECONDS.toNanos(6))); Assertions.assertEquals("30s", f.apply(TimeUnit.SECONDS.toNanos(7))); Assertions.assertEquals("30s", f.apply(TimeUnit.SECONDS.toNanos(10))); Assertions.assertEquals("30s", f.apply(TimeUnit.SECONDS.toNanos(20))); Assertions.assertEquals("30s", f.apply(TimeUnit.SECONDS.toNanos(30))); Assertions.assertEquals("45s", f.apply(TimeUnit.SECONDS.toNanos(42))); Assertions.assertEquals("52s", f.apply(TimeUnit.SECONDS.toNanos(48))); Assertions.assertEquals("60s", f.apply(TimeUnit.SECONDS.toNanos(59))); Assertions.assertEquals("60s", f.apply(TimeUnit.SECONDS.toNanos(60))); Assertions.assertEquals("old", f.apply(TimeUnit.SECONDS.toNanos(61))); } @Test public void latency100ms() { LongFunction<String> f = BucketFunctions.latency(100, TimeUnit.MILLISECONDS); Assertions.assertEquals("negative_latency", f.apply(TimeUnit.MILLISECONDS.toNanos(-1))); Assertions.assertEquals("012ms", f.apply(TimeUnit.MILLISECONDS.toNanos(0))); Assertions.assertEquals("012ms", f.apply(TimeUnit.MILLISECONDS.toNanos(1))); Assertions.assertEquals("025ms", f.apply(TimeUnit.MILLISECONDS.toNanos(13))); Assertions.assertEquals("025ms", f.apply(TimeUnit.MILLISECONDS.toNanos(25))); Assertions.assertEquals("100ms", f.apply(TimeUnit.MILLISECONDS.toNanos(99))); Assertions.assertEquals("slow", f.apply(TimeUnit.MILLISECONDS.toNanos(101))); } @Test public void latency100msBiasSlow() { LongFunction<String> f = BucketFunctions.latencyBiasSlow(100, TimeUnit.MILLISECONDS); Assertions.assertEquals("negative_latency", f.apply(TimeUnit.MILLISECONDS.toNanos(-1))); Assertions.assertEquals("050ms", f.apply(TimeUnit.MILLISECONDS.toNanos(0))); Assertions.assertEquals("050ms", f.apply(TimeUnit.MILLISECONDS.toNanos(1))); Assertions.assertEquals("050ms", f.apply(TimeUnit.MILLISECONDS.toNanos(13))); Assertions.assertEquals("050ms", f.apply(TimeUnit.MILLISECONDS.toNanos(25))); Assertions.assertEquals("075ms", f.apply(TimeUnit.MILLISECONDS.toNanos(74))); Assertions.assertEquals("075ms", f.apply(TimeUnit.MILLISECONDS.toNanos(75))); Assertions.assertEquals("087ms", f.apply(TimeUnit.MILLISECONDS.toNanos(76))); Assertions.assertEquals("100ms", f.apply(TimeUnit.MILLISECONDS.toNanos(99))); Assertions.assertEquals("slow", f.apply(TimeUnit.MILLISECONDS.toNanos(101))); } @Test public void latency3s() { LongFunction<String> f = BucketFunctions.latency(3, TimeUnit.SECONDS); Assertions.assertEquals("negative_latency", f.apply(TimeUnit.MILLISECONDS.toNanos(-1))); Assertions.assertEquals("0375ms", f.apply(TimeUnit.MILLISECONDS.toNanos(0))); Assertions.assertEquals("0375ms", f.apply(TimeUnit.MILLISECONDS.toNanos(25))); Assertions.assertEquals("0750ms", f.apply(TimeUnit.MILLISECONDS.toNanos(740))); Assertions.assertEquals("1500ms", f.apply(TimeUnit.MILLISECONDS.toNanos(1000))); Assertions.assertEquals("3000ms", f.apply(TimeUnit.MILLISECONDS.toNanos(1567))); Assertions.assertEquals("slow", f.apply(TimeUnit.MILLISECONDS.toNanos(3001))); } @Test public void latencyRange() { for (BucketFunctions.ValueFormatter fmt : BucketFunctions.TIME_FORMATTERS) { final long max = fmt.max(); LongFunction<String> f = BucketFunctions.latency(max, TimeUnit.NANOSECONDS); Set<String> keys = new HashSet<>(); final long step = (max > 37) ? max / 37 : 1; for (long j = 0L; max - j > step; j += step) { keys.add(f.apply(j)); } keys.add(f.apply(max)); Assertions.assertEquals(4, keys.size()); } } @Test public void latencyBiasSlowRange() { for (BucketFunctions.ValueFormatter fmt : BucketFunctions.TIME_FORMATTERS) { final long max = fmt.max(); LongFunction<String> f = BucketFunctions.latencyBiasSlow(max, TimeUnit.NANOSECONDS); Set<String> keys = new HashSet<>(); final long step = (max > 37) ? max / 37 : 1; for (long j = 0L; max - j >= step; j += step) { keys.add(f.apply(j)); } keys.add(f.apply(max)); Assertions.assertEquals(4, keys.size()); } } @Test public void bytes1K() { LongFunction<String> f = BucketFunctions.bytes(1024); Assertions.assertEquals("negative", f.apply(-1L)); Assertions.assertEquals("0256_B", f.apply(212)); Assertions.assertEquals("0512_B", f.apply(512)); Assertions.assertEquals("1024_B", f.apply(761)); Assertions.assertEquals("large", f.apply(20001)); } @Test public void bytes20K() { LongFunction<String> f = BucketFunctions.bytes(20000); Assertions.assertEquals("negative", f.apply(-1L)); Assertions.assertEquals("02_KiB", f.apply(761)); Assertions.assertEquals("04_KiB", f.apply(4567)); Assertions.assertEquals("19_KiB", f.apply(15761)); Assertions.assertEquals("large", f.apply(20001)); } @Test public void bytes2M() { LongFunction<String> f = BucketFunctions.bytes(2 * 1024 * 1024); Assertions.assertEquals("negative", f.apply(-1L)); Assertions.assertEquals("0256_KiB", f.apply(761)); Assertions.assertEquals("0512_KiB", f.apply(400_000)); Assertions.assertEquals("1024_KiB", f.apply(512 * 1024 + 1)); Assertions.assertEquals("large", f.apply(2 * 1024 * 1024 + 1)); } @Test public void bytesMaxValue() { LongFunction<String> f = BucketFunctions.bytes(Long.MAX_VALUE); Assertions.assertEquals("negative", f.apply(-1L)); Assertions.assertEquals("1023_PiB", f.apply(761)); Assertions.assertEquals("2047_PiB", f.apply(Long.MAX_VALUE / 4)); Assertions.assertEquals("4095_PiB", f.apply(Long.MAX_VALUE / 2)); Assertions.assertEquals("8191_PiB", f.apply(Long.MAX_VALUE)); } @Test public void decimal20K() { LongFunction<String> f = BucketFunctions.decimal(20000); Assertions.assertEquals("negative", f.apply(-1L)); Assertions.assertEquals("02_k", f.apply(761)); Assertions.assertEquals("05_k", f.apply(4567)); Assertions.assertEquals("20_k", f.apply(15761)); Assertions.assertEquals("large", f.apply(20001)); } @Test public void decimal2M() { LongFunction<String> f = BucketFunctions.decimal(2_000_000); Assertions.assertEquals("negative", f.apply(-1L)); Assertions.assertEquals("0250_k", f.apply(761)); Assertions.assertEquals("0500_k", f.apply(456_000)); Assertions.assertEquals("1000_k", f.apply(576_100)); Assertions.assertEquals("large", f.apply(2_000_001)); } @Test public void decimalMaxValue() { LongFunction<String> f = BucketFunctions.decimal(Long.MAX_VALUE); Assertions.assertEquals("negative", f.apply(-1L)); Assertions.assertEquals("1_E", f.apply(761)); Assertions.assertEquals("2_E", f.apply(Long.MAX_VALUE / 4)); Assertions.assertEquals("4_E", f.apply(Long.MAX_VALUE / 2)); Assertions.assertEquals("9_E", f.apply(Long.MAX_VALUE)); } }
5,726
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/histogram/BucketDistributionSummaryTest.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api.histogram; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.DistributionSummary; import com.netflix.spectator.api.Functions; import com.netflix.spectator.api.Registry; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; public class BucketDistributionSummaryTest { private long sum(Registry r, String name) { return r.distributionSummaries() .filter(Functions.nameEquals(name)) .mapToLong(DistributionSummary::count) .sum(); } @Test public void basic() { Registry r = new DefaultRegistry(); BucketDistributionSummary c = BucketDistributionSummary.get( r, r.createId("test"), BucketFunctions.latency(4, TimeUnit.SECONDS)); c.record(TimeUnit.MILLISECONDS.toNanos(3750)); Assertions.assertEquals(1, r.distributionSummaries().count()); Assertions.assertEquals(1, sum(r, "test")); c.record(TimeUnit.MILLISECONDS.toNanos(4221)); Assertions.assertEquals(2, r.distributionSummaries().count()); Assertions.assertEquals(2, sum(r, "test")); c.record(TimeUnit.MILLISECONDS.toNanos(4221)); Assertions.assertEquals(2, r.distributionSummaries().count()); Assertions.assertEquals(3, sum(r, "test")); } }
5,727
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/histogram/PercentileTimerTest.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api.histogram; import com.netflix.spectator.api.Clock; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.ExpiringRegistry; import com.netflix.spectator.api.ManualClock; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Spectator; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.time.Duration; import java.util.concurrent.TimeUnit; public class PercentileTimerTest { private Registry newRegistry() { return new DefaultRegistry(Clock.SYSTEM, k -> null); } private void checkPercentiles(PercentileTimer t, int start) { for (int i = 0; i < 100_000; ++i) { t.record(i, TimeUnit.MILLISECONDS); } for (int i = start; i <= 100; ++i) { double expected = (double) i; double threshold = 0.15 * expected + 1e-12; Assertions.assertEquals(expected, t.percentile(i), threshold); } } @Test public void percentile() { Registry r = newRegistry(); PercentileTimer t = PercentileTimer.get(r, r.createId("test")); checkPercentiles(t, 0); } @Test public void builderWithThreshold() { Registry r = newRegistry(); PercentileTimer t = PercentileTimer.builder(r) .withName("test") .withRange(10, 100, TimeUnit.SECONDS) .build(); checkPercentiles(t, 10); } @Test public void builderWithThresholdDuration() { Registry r = newRegistry(); PercentileTimer t = PercentileTimer.builder(r) .withName("test") .withRange(Duration.ZERO, Duration.ofSeconds(100)) .build(); checkPercentiles(t, 0); } private void checkValue(PercentileTimer t1, PercentileTimer t2, double expected) { Assertions.assertEquals(expected, t1.percentile(99.0), expected / 5.0); Assertions.assertEquals(expected, t2.percentile(99.0), expected / 5.0); } @Test public void builderWithDifferentThresholds() { Registry r = newRegistry(); PercentileTimer t1 = PercentileTimer.builder(r) .withName("test") .withRange(10, 50, TimeUnit.SECONDS) .build(); PercentileTimer t2 = PercentileTimer.builder(r) .withName("test") .withRange(100, 200, TimeUnit.SECONDS) .build(); t1.record(5, TimeUnit.SECONDS); checkValue(t1, t2, 10.0); t1.record(500, TimeUnit.SECONDS); checkValue(t1, t2, 50.0); t2.record(5, TimeUnit.SECONDS); checkValue(t1, t2, 100.0); t2.record(500, TimeUnit.SECONDS); checkValue(t1, t2, 200.0); } @Test public void expiration() { ManualClock clock = new ManualClock(); ExpiringRegistry r = new ExpiringRegistry(clock); PercentileTimer t = PercentileTimer.builder(r) .withName("test") .build(); Assertions.assertFalse(t.hasExpired()); t.record(5, TimeUnit.SECONDS); Assertions.assertEquals(1, r.timer("test").count()); clock.setWallTime(1); Assertions.assertTrue(t.hasExpired()); r.removeExpiredMeters(); Assertions.assertNull(r.state().get(t.id())); t.record(5, TimeUnit.SECONDS); Assertions.assertFalse(t.hasExpired()); Assertions.assertEquals(1, r.timer("test").count()); } @Test public void expirationGlobalRegistry() { ManualClock clock = new ManualClock(); ExpiringRegistry r = new ExpiringRegistry(clock); Spectator.globalRegistry().removeAll(); Spectator.globalRegistry().add(r); PercentileTimer t = PercentileTimer.builder(Spectator.globalRegistry()) .withName("test") .build(); Assertions.assertFalse(t.hasExpired()); t.record(5, TimeUnit.SECONDS); Assertions.assertEquals(1, r.timer("test").count()); clock.setWallTime(1); Assertions.assertTrue(t.hasExpired()); r.removeExpiredMeters(); Assertions.assertNull(r.state().get(t.id())); t.record(5, TimeUnit.SECONDS); Assertions.assertFalse(t.hasExpired()); Assertions.assertEquals(1, r.timer("test").count()); } }
5,728
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/histogram/PercentileDistributionSummaryTest.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api.histogram; import com.netflix.spectator.api.Clock; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Registry; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class PercentileDistributionSummaryTest { private Registry newRegistry() { return new DefaultRegistry(Clock.SYSTEM, k -> null); } private void checkPercentiles(PercentileDistributionSummary t, int start) { for (int i = 0; i < 100_000; ++i) { t.record(i); } for (int i = start; i <= 100; ++i) { double expected = i * 1000.0; double threshold = 0.15 * expected + 1e-12; Assertions.assertEquals(expected, t.percentile(i), threshold); } } @Test public void percentile() { Registry r = newRegistry(); PercentileDistributionSummary t = PercentileDistributionSummary.get(r, r.createId("test")); checkPercentiles(t, 0); } @Test public void builder() { Registry r = newRegistry(); PercentileDistributionSummary t = PercentileDistributionSummary.builder(r) .withName("test") .build(); checkPercentiles(t, 0); } @Test public void builderWithThreshold() { Registry r = newRegistry(); PercentileDistributionSummary t = PercentileDistributionSummary.builder(r) .withName("test") .withRange(25_000, 100_000) .build(); checkPercentiles(t, 25); } private void checkValue(PercentileDistributionSummary t1, PercentileDistributionSummary t2, double expected) { Assertions.assertEquals(expected, t1.percentile(99.0), expected / 5.0); Assertions.assertEquals(expected, t2.percentile(99.0), expected / 5.0); } @Test public void builderWithDifferentThresholds() { Registry r = newRegistry(); PercentileDistributionSummary t1 = PercentileDistributionSummary.builder(r) .withName("test") .withRange(10, 50) .build(); PercentileDistributionSummary t2 = PercentileDistributionSummary.builder(r) .withName("test") .withRange(100, 200) .build(); t1.record(5); checkValue(t1, t2, 10.0); t1.record(500); checkValue(t1, t2, 50.0); t2.record(5); checkValue(t1, t2, 100.0); t2.record(500); checkValue(t1, t2, 200.0); } }
5,729
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/Preconditions.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl; /** * Internal convenience methods that help a method or constructor check whether it was invoked * correctly. * * <p><b>This class is an internal implementation detail only intended for use within spectator. * It is subject to change without notice.</b></p> */ public final class Preconditions { private Preconditions() { } /** * Ensures the object reference is not null. */ public static <T> T checkNotNull(T obj, String name) { if (obj == null) { String msg = String.format("parameter '%s' cannot be null", name); throw new NullPointerException(msg); } return obj; } /** * Ensures the truth of an expression involving the state of the calling instance. */ public static void checkArg(boolean expression, String errMsg) { if (!expression) { throw new IllegalArgumentException(errMsg); } } /** * Ensures the truth of an expression involving the state of the calling instance. */ public static void checkState(boolean expression, String errMsg) { if (!expression) { throw new IllegalStateException(errMsg); } } }
5,730
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/LfuCache.java
/* * Copyright 2014-2021 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.Registry; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.LongAdder; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Function; import java.util.stream.Collectors; /** * LFU implementation of {@link Cache}. */ class LfuCache<K, V> implements Cache<K, V> { private final Counter hits; private final Counter misses; private final Counter compactions; private final ConcurrentHashMap<K, Pair<V>> data; private final int baseSize; private final int compactionSize; // Collections that are reused for each compaction operation private final PriorityQueue<Snapshot<K>> mostFrequentItems; private final List<K> mostFrequentKeys; private final AtomicInteger size; private final Lock lock; LfuCache(Registry registry, String id, int baseSize, int compactionSize) { this.hits = registry.counter("spectator.cache.requests", "id", id, "result", "hit"); this.misses = registry.counter("spectator.cache.requests", "id", id, "result", "miss"); this.compactions = registry.counter("spectator.cache.compactions", "id", id); data = new ConcurrentHashMap<>(); this.baseSize = baseSize; this.compactionSize = compactionSize; this.mostFrequentItems = new PriorityQueue<>(baseSize, SNAPSHOT_COMPARATOR); this.mostFrequentKeys = new ArrayList<>(baseSize); this.size = new AtomicInteger(); this.lock = new ReentrantLock(); } private void addIfMoreFrequent(K key, Pair<V> value) { long count = value.snapshot(); if (mostFrequentItems.size() >= baseSize) { // Queue is full, add new item if it is more frequently used than the least // frequent item currently in the queue. Snapshot<K> leastFrequentItem = mostFrequentItems.peek(); if (leastFrequentItem != null && count > leastFrequentItem.count()) { mostFrequentItems.poll(); mostFrequentItems.offer(new Snapshot<>(key, count)); } } else { mostFrequentItems.offer(new Snapshot<>(key, count)); } } private void compact() { int numToRemove = size.get() - baseSize; if (numToRemove > 0) { mostFrequentItems.clear(); mostFrequentKeys.clear(); data.forEach(this::addIfMoreFrequent); mostFrequentItems.forEach(s -> mostFrequentKeys.add(s.get())); data.keySet().retainAll(mostFrequentKeys); size.set(data.size()); compactions.increment(); } } private void tryCompact() { if (lock.tryLock()) { try { compact(); } finally { lock.unlock(); } } } @Override public V get(K key) { Pair<V> value = data.get(key); if (value == null) { misses.increment(); return null; } else { hits.increment(); return value.get(); } } @Override public V peek(K key) { Pair<V> value = data.get(key); return value == null ? null : value.peek(); } @Override public void put(K key, V value) { Pair<V> prev = data.put(key, new Pair<>(value)); if (prev == null && size.incrementAndGet() > compactionSize) { tryCompact(); } } @Override public V computeIfAbsent(K key, Function<K, V> f) { Pair<V> value = data.get(key); if (value == null) { misses.increment(); Pair<V> tmp = new Pair<>(f.apply(key)); value = data.putIfAbsent(key, tmp); if (value == null) { value = tmp; if (size.incrementAndGet() > compactionSize) { tryCompact(); } } } else { hits.increment(); } return value.get(); } @Override public void clear() { size.set(0); data.clear(); } @Override public int size() { return size.get(); } @Override public Map<K, V> asMap() { return data.entrySet() .stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().peek())); } private static class Pair<V> { private final V value; private final LongAdder count; Pair(V value) { this.value = value; this.count = new LongAdder(); } V get() { count.increment(); return value; } V peek() { return value; } long snapshot() { return count.sum(); } } private static class Snapshot<K> { private final K key; private final long count; Snapshot(K key, long count) { this.key = key; this.count = count; } K get() { return key; } long count() { return count; } } // Comparator for finding the least frequent items with the priority queue private static final Comparator<Snapshot<?>> SNAPSHOT_COMPARATOR = (a, b) -> Long.compare(b.count(), a.count()); }
5,731
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/StepLong.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl; import com.netflix.spectator.api.Clock; import java.util.concurrent.atomic.AtomicLong; /** * Utility class for managing a set of AtomicLong instances mapped to a particular step interval. * The current implementation keeps an array of with two items where one is the current value * being updated and the other is the value from the previous interval and is only available for * polling. * * <p><b>This class is an internal implementation detail only intended for use within spectator. * It is subject to change without notice.</b></p> */ public class StepLong implements StepValue { private final long init; private final Clock clock; private final long step; private volatile long previous; private final AtomicLong current; private final AtomicLong lastInitPos; /** Create a new instance. */ public StepLong(long init, Clock clock, long step) { this.init = init; this.clock = clock; this.step = step; previous = init; current = new AtomicLong(init); lastInitPos = new AtomicLong(clock.wallTime() / step); } private void rollCount(long now) { final long stepTime = now / step; final long lastInit = lastInitPos.get(); if (lastInit < stepTime && lastInitPos.compareAndSet(lastInit, stepTime)) { final long v = current.getAndSet(init); // Need to check if there was any activity during the previous step interval. If there was // then the init position will move forward by 1, otherwise it will be older. No activity // means the previous interval should be set to the `init` value. previous = (lastInit == stepTime - 1) ? v : init; } } /** Get the AtomicLong for the current bucket. */ public AtomicLong getCurrent() { return getCurrent(clock.wallTime()); } /** Get the AtomicLong for the current bucket. */ public AtomicLong getCurrent(long now) { rollCount(now); return current; } /** Get the value for the last completed interval. */ public long poll() { return poll(clock.wallTime()); } /** Get the value for the last completed interval. */ public long poll(long now) { rollCount(now); return previous; } /** Get the value for the last completed interval as a rate per second. */ @Override public double pollAsRate() { return pollAsRate(clock.wallTime()); } /** Get the value for the last completed interval as a rate per second. */ @Override public double pollAsRate(long now) { final long amount = poll(now); final double period = step / 1000.0; return amount / period; } /** Get the timestamp for the end of the last completed interval. */ @Override public long timestamp() { return lastInitPos.get() * step; } @Override public String toString() { return "StepLong{init=" + init + ", previous=" + previous + ", current=" + current.get() + ", lastInitPos=" + lastInitPos.get() + '}'; } }
5,732
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/AtomicDouble.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl; import java.util.concurrent.atomic.AtomicLong; /** * Wrapper around AtomicLong to make working with double values easier. * * <p><b>This class is an internal implementation detail only intended for use within spectator. * It is subject to change without notice.</b></p> */ @SuppressWarnings("PMD.MissingSerialVersionUID") public class AtomicDouble extends Number { private final AtomicLong value; /** Create an instance with an initial value of 0. */ public AtomicDouble() { this(0.0); } /** Create an instance with an initial value of {@code init}. */ public AtomicDouble(double init) { super(); value = new AtomicLong(Double.doubleToLongBits(init)); } /** Return the current value. */ public double get() { return Double.longBitsToDouble(value.get()); } /** Add {@code amount} to the value and return the new value. */ public double addAndGet(double amount) { long v; double d; double n; long next; do { v = value.get(); d = Double.longBitsToDouble(v); n = d + amount; next = Double.doubleToLongBits(n); } while (!value.compareAndSet(v, next)); return n; } /** Add {@code amount} to the value and return the previous value. */ public double getAndAdd(double amount) { long v; double d; double n; long next; do { v = value.get(); d = Double.longBitsToDouble(v); n = d + amount; next = Double.doubleToLongBits(n); } while (!value.compareAndSet(v, next)); return d; } /** Set the value to {@code amount} and return the previous value. */ public double getAndSet(double amount) { long v = value.getAndSet(Double.doubleToLongBits(amount)); return Double.longBitsToDouble(v); } /** * Set the value to {@code amount} if the current value is {@code expect}. Return true if the * value was updated. */ public boolean compareAndSet(double expect, double update) { long e = Double.doubleToLongBits(expect); long u = Double.doubleToLongBits(update); return value.compareAndSet(e, u); } /** Set the current value to {@code amount}. */ public void set(double amount) { value.set(Double.doubleToLongBits(amount)); } private boolean isGreaterThan(double v1, double v2) { return v1 > v2 || Double.isNaN(v2); } /** Set the current value to the maximum of the current value or the provided value. */ public void max(double v) { if (Double.isFinite(v)) { double max = get(); while (isGreaterThan(v, max) && !compareAndSet(max, v)) { max = get(); } } } @Override public int intValue() { return (int) get(); } @Override public long longValue() { return (long) get(); } @Override public float floatValue() { return (float) get(); } @Override public double doubleValue() { return get(); } }
5,733
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/SwapMeter.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Measurement; import com.netflix.spectator.api.Meter; import com.netflix.spectator.api.Registry; import java.util.function.LongSupplier; /** * Base type for meters that allow the underlying implementation to be replaced with * another. This is used by {@link com.netflix.spectator.api.AbstractRegistry} as the * basis for expiring types where a user may have a reference in their code. * * <p><b>This class is an internal implementation detail only intended for use within * spectator. It is subject to change without notice.</b></p> */ public abstract class SwapMeter<T extends Meter> implements Meter { /** Registry used to lookup values after expiration. */ protected final Registry registry; private final LongSupplier versionSupplier; private volatile long currentVersion; /** Id to use when performing a lookup after expiration. */ protected final Id id; /** Current meter to delegate operations. */ private volatile T underlying; /** Create a new instance. */ public SwapMeter(Registry registry, LongSupplier versionSupplier, Id id, T underlying) { this.registry = registry; this.versionSupplier = versionSupplier; this.currentVersion = versionSupplier.getAsLong(); this.id = id; this.underlying = unwrap(underlying); } /** * Lookup the meter from the registry. */ public abstract T lookup(); @Override public Id id() { return id; } @Override public Iterable<Measurement> measure() { return get().measure(); } @Override public boolean hasExpired() { return currentVersion < versionSupplier.getAsLong() || underlying.hasExpired(); } /** * Set the underlying instance of the meter to use. This can be set to {@code null} * to indicate that the meter has expired and is no longer in the registry. */ public void set(T meter) { underlying = unwrap(meter); } /** Return the underlying instance of the meter. */ public T get() { if (hasExpired()) { currentVersion = versionSupplier.getAsLong(); underlying = unwrap(lookup()); } return underlying; } /** * If the values are nested, then unwrap any that have the same registry instance. */ @SuppressWarnings("unchecked") private T unwrap(T meter) { T tmp = meter; while (tmp instanceof SwapMeter<?> && registry == ((SwapMeter<?>) tmp).registry) { tmp = ((SwapMeter<T>) tmp).underlying; } return tmp; } }
5,734
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/Scheduler.java
/* * Copyright 2014-2023 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl; import com.netflix.spectator.api.Clock; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Timer; import com.netflix.spectator.api.patterns.PolledMeter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Duration; import java.util.concurrent.DelayQueue; import java.util.concurrent.Delayed; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * <p><b>This class is an internal implementation detail only intended for use within spectator. * It is subject to change without notice.</b></p> * * <p>Simple scheduler for recurring tasks based on a fixed size thread pool. This * class is mostly intended for running short lived tasks at a regular interval.</p> * * <p><b>Usage</b></p> * * <pre> * Scheduler scheduler = new Scheduler(registry, "spectator-polling", 2); * * Scheduler.Options options = new Scheduler.Options() * .withFrequency(Scheduler.Policy.FIXED_RATE_SKIP_IF_LONG, Duration.ofSeconds(10)); * scheduler.schedule(options, () -> doWork()); * </pre> * * <p><b>Metrics</b></p> * * The following metrics can be used to monitor the behavior of the scheduler: * * <ul> * <li><code>spectator.scheduler.queueSize</code>: gauge reporting the number of * items in the queue. Note, that for repeating tasks the items will almost * always be in queue except during execution.</li> * <li><code>spectator.scheduler.poolSize</code>: gauge reporting the number of * threads available in the pool.</li> * <li><code>spectator.scheduler.activeThreads</code>: gauge reporting the number of * threads that are currently executing a task.</li> * <li><code>spectator.scheduler.taskExecutionTime</code>: timer reporting the * execution time of an individual task.</li> * <li><code>spectator.scheduler.taskExecutionDelay</code>: timer reporting the * delay between the desired execution time of a task and when it was actually * executed. A high execution delay means that the scheduler cannot keep up * with the amount of work. This might indicate more threads are needed.</li> * <li><code>spectator.scheduler.skipped</code>: counter reporting the number of * executions that were skipped because the task did not complete before the * next scheduled execution time.</li> * <li><code>spectator.scheduler.uncaughtExceptions</code>: counter reporting the * number of times an exception is propagated out from a task.</li> * </ul> * * All metrics with have an {@code id} dimension to distinguish a particular scheduler * instance. */ public class Scheduler { /** * Create a thread factory using thread names based on the id. All threads will * be configured as daemon threads. */ private static ThreadFactory newThreadFactory(final String id) { return new ThreadFactory() { private final AtomicInteger next = new AtomicInteger(); @Override public Thread newThread(Runnable r) { final String name = "spectator-" + id + "-" + next.getAndIncrement(); final Thread t = new Thread(r, name); t.setDaemon(true); return t; } }; } private static Id newId(Registry registry, String id, String name) { return registry.createId("spectator.scheduler." + name, "id", id); } private static final Logger LOGGER = LoggerFactory.getLogger(Scheduler.class); private final DelayQueue<DelayedTask> queue = new DelayQueue<>(); private final Clock clock; private final Stats stats; private final ThreadFactory factory; private final Thread[] threads; private final Lock lock = new ReentrantLock(); private volatile boolean started = false; private volatile boolean shutdown = false; /** * Create a new instance. * * @param registry * Registry to use for collecting metrics. The clock from the registry will also be * used as the clock source for accessing the time. * @param id * Id for this instance of the scheduler. Used to distinguish between instances of * the scheduler for metrics and thread names. Threads will be named as * {@code spectator-$id-$i}. * @param poolSize * Number of threads to have in the pool. The threads will not be started until the * first task is scheduled. */ public Scheduler(Registry registry, String id, int poolSize) { this.clock = registry.clock(); PolledMeter.using(registry) .withId(newId(registry, id, "queueSize")) .monitorSize(queue); stats = new Stats(registry, id); this.factory = newThreadFactory(id); this.threads = new Thread[poolSize]; } /** * Schedule a repetitive task. * * @param options * Options for controlling the execution of the task. See {@link Options} * for more information. * @param task * Task to execute. * @return * Future that can be used for cancelling the current and future executions of * the task. There is no value associated with the task so the future is just for * checking if it is still running to stopping it from running in the future. */ public ScheduledFuture<?> schedule(Options options, Runnable task) { if (!started) { startThreads(); } DelayedTask t = new DelayedTask(clock, options, task); queue.put(t); return t; } /** * Shutdown and cleanup resources associated with the scheduler. All threads will be * interrupted, but this method does not block for them to all finish execution. */ public void shutdown() { lock.lock(); try { shutdown = true; for (int i = 0; i < threads.length; ++i) { if (threads[i] != null && threads[i].isAlive()) { threads[i].interrupt(); threads[i] = null; } } } finally { lock.unlock(); } } private void startThreads() { lock.lock(); try { if (!shutdown) { started = true; for (int i = 0; i < threads.length; ++i) { if (threads[i] == null || !threads[i].isAlive() || threads[i].isInterrupted()) { threads[i] = factory.newThread(new Worker()); threads[i].start(); LOGGER.debug("started thread {}", threads[i].getName()); } } } } finally { lock.unlock(); } } /** Repetition schedulingPolicy for scheduled tasks. */ public enum Policy { /** Run a task once. */ RUN_ONCE, /** Run a task repeatedly using a fixed delay between executions. */ FIXED_DELAY, /** * Run a task repeatedly attempting to maintain a consistent rate of execution. * If the execution time is less than the desired frequencyMillis, then the start times * will be at a consistent interval. If the execution time exceeds the frequencyMillis, * then some executions will be skipped. * * The primary use case for this mode is when we want to maintain a consistent * frequencyMillis, but want to avoid queuing up many tasks if the system cannot keep * up. Fixed delay is often inappropriate because for the normal case it will * drift by the execution time of the task. */ FIXED_RATE_SKIP_IF_LONG } /** Options to control how a task will get executed. */ public static class Options { private Policy schedulingPolicy = Policy.RUN_ONCE; private long initialDelay = 0L; private long frequencyMillis = 0L; private boolean stopOnFailure = false; /** * How long to wait after a task has been scheduled to the first execution. If * not set, then it will be scheduled immediately. */ public Options withInitialDelay(Duration delay) { initialDelay = delay.toMillis(); return this; } /** * Configure the task to execute repeatedly. * * @param policy * Repetition schedulingPolicy to use for the task. See {@link Policy} for the * supported options. * @param frequency * How frequently to repeat the execution. The interpretation of this * parameter will depend on the {@link Policy}. */ public Options withFrequency(Policy policy, Duration frequency) { this.schedulingPolicy = policy; this.frequencyMillis = frequency.toMillis(); return this; } /** * Should a repeated task stop executing if an exception propagates out of * the task? Defaults to false. */ public Options withStopOnFailure(boolean flag) { this.stopOnFailure = flag; return this; } } /** * Collection of stats that are updated as part of executing the tasks. */ static class Stats { private final Registry registry; private final AtomicInteger activeCount; private final Timer taskExecutionTime; private final Timer taskExecutionDelay; private final Counter skipped; private final Id uncaughtExceptionsId; /** Create a new instance. */ Stats(Registry registry, String id) { this.registry = registry; activeCount = PolledMeter.using(registry) .withId(newId(registry, id, "activeThreads")) .monitorValue(new AtomicInteger()); taskExecutionTime = registry.timer(newId(registry, id, "taskExecutionTime")); taskExecutionDelay = registry.timer(newId(registry, id, "taskExecutionDelay")); skipped = registry.counter(newId(registry, id, "skipped")); uncaughtExceptionsId = newId(registry, id, "uncaughtExceptions"); } /** Increment the number of active tasks. */ void incrementActiveTaskCount() { activeCount.incrementAndGet(); } /** Decrement the number of active tasks. */ void decrementActiveTaskCount() { activeCount.decrementAndGet(); } /** Timer for measuring the execution time of the task. */ Timer taskExecutionTime() { return taskExecutionTime; } /** * Timer for measuring the delay for the task. This should be close to zero, but if * the system is overloaded or having trouble, then there might be a large delay. */ Timer taskExecutionDelay() { return taskExecutionDelay; } /** * Counter that will be incremented each time an expected execution is * skipped when using {@link Policy#FIXED_RATE_SKIP_IF_LONG}. */ Counter skipped() { return skipped; } /** * Increment the uncaught exception counter tagged with simple class name of the * exception. */ void incrementUncaught(Throwable t) { final String cls = t.getClass().getSimpleName(); registry.counter(uncaughtExceptionsId.withTag("exception", cls)).increment(); } } /** * Wraps the user supplied task with metadata for subsequent executions. */ static class DelayedTask implements ScheduledFuture<Void> { private final Clock clock; private final Options options; private final Runnable task; private final long initialExecutionTime; private long nextExecutionTime; private volatile Thread thread = null; private volatile boolean cancelled = false; /** * Create a new instance. * * @param clock * Clock for computing the next execution time for the task. * @param options * Options for how to repeat the execution. * @param task * User specified task to execute. */ DelayedTask(Clock clock, Options options, Runnable task) { this.clock = clock; this.options = options; this.task = task; this.initialExecutionTime = clock.wallTime() + options.initialDelay; this.nextExecutionTime = initialExecutionTime; } /** Returns the next scheduled execution time. */ long getNextExecutionTime() { return nextExecutionTime; } /** * Update the next execution time based on the options for this task. * * @param skipped * Counter that will be incremented each time an expected execution is * skipped when using {@link Policy#FIXED_RATE_SKIP_IF_LONG}. */ void updateNextExecutionTime(Counter skipped) { switch (options.schedulingPolicy) { case FIXED_DELAY: nextExecutionTime = clock.wallTime() + options.frequencyMillis; break; case FIXED_RATE_SKIP_IF_LONG: final long now = clock.wallTime(); nextExecutionTime += options.frequencyMillis; while (nextExecutionTime < now) { nextExecutionTime += options.frequencyMillis; skipped.increment(); } break; default: break; } } /** * Execute the task and if reschedule another execution. * * @param queue * Queue for the pool. This task will be added to the queue to schedule * future executions. * @param stats * Handle to stats that should be updated based on the execution of the * task. */ @SuppressWarnings("PMD.AvoidCatchingThrowable") void runAndReschedule(DelayQueue<DelayedTask> queue, Stats stats) { thread = Thread.currentThread(); boolean scheduleAgain = options.schedulingPolicy != Policy.RUN_ONCE; try { if (!isDone()) { task.run(); } } catch (Throwable t) { // This catches Throwable because we cannot control the task and thus cannot // ensure it is well behaved with respect to exceptions. LOGGER.warn("task execution failed", t); stats.incrementUncaught(t); scheduleAgain = !options.stopOnFailure; } finally { thread = null; if (scheduleAgain && !isDone()) { updateNextExecutionTime(stats.skipped()); queue.put(this); } else { cancelled = true; } } } @Override public long getDelay(TimeUnit unit) { final long delayMillis = Math.max(nextExecutionTime - clock.wallTime(), 0L); return unit.convert(delayMillis, TimeUnit.MILLISECONDS); } @Override public int compareTo(Delayed other) { final long d1 = getDelay(TimeUnit.MILLISECONDS); final long d2 = other.getDelay(TimeUnit.MILLISECONDS); return Long.compare(d1, d2); } @Override public boolean cancel(boolean mayInterruptIfRunning) { cancelled = true; Thread t = thread; if (mayInterruptIfRunning && t != null) { t.interrupt(); } return true; } @Override public boolean isCancelled() { return cancelled; } @Override public boolean isDone() { return cancelled; } @Override public Void get() throws InterruptedException, ExecutionException { throw new UnsupportedOperationException(); } @Override public Void get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { throw new UnsupportedOperationException(); } } /** * Actual task running in the threads. It will block on trying to get a task to * execute from the queue until a task is ready. */ private final class Worker implements Runnable { @Override public void run() { try { // Note: do not use Thread.interrupted() because it will clear the interrupt // status of the thread. while (!Thread.currentThread().isInterrupted()) { try { DelayedTask task = queue.take(); stats.incrementActiveTaskCount(); final long delay = clock.wallTime() - task.getNextExecutionTime(); stats.taskExecutionDelay().record(delay, TimeUnit.MILLISECONDS); stats.taskExecutionTime().recordRunnable(() -> task.runAndReschedule(queue, stats)); } catch (InterruptedException e) { LOGGER.debug("task interrupted", e); break; } finally { stats.decrementActiveTaskCount(); } } } finally { startThreads(); } } } }
5,735
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/Cache.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl; import com.netflix.spectator.api.Registry; import java.util.Map; import java.util.function.Function; /** * Simple in-memory cache based on ConcurrentHashMap with minimal dependencies. * * <p><b>This class is an internal implementation detail only intended for use within spectator. * It is subject to change without notice.</b></p> */ public interface Cache<K, V> { /** * Create a new cache instance that removes the least frequently used items when full. * * @param registry * Registry to use for tracking stats about the cache. * @param id * Used with metrics to indentify a particular instance of the cache. * @param baseSize * Number of items that should always be kept around in the cache. * @param compactionSize * Maximum size of the underlying map for the cache. * @return * Instance of an LFU cache. */ static <K1, V1> Cache<K1, V1> lfu(Registry registry, String id, int baseSize, int compactionSize) { return new LfuCache<>(registry, id, baseSize, compactionSize); } /** * Returns the cached value associated with the key or null if none is found. */ V get(K key); /** * Like {@link #get(Object)}, but does not update the access count. */ V peek(K key); /** * Add or overwrite the cache entry for the key. */ void put(K key, V value); /** * Returns the cached value associated with the key if present, otherwise computes a value * using the provided function. * * @param key * Id to use for looking up a value in the cache. * @param f * Function to compute a value based on the key. This function may get called multiple * times on a cache miss with some results getting discarded. * @return * The value that was already cached or was just computed. */ V computeIfAbsent(K key, Function<K, V> f); /** * Remove all entries from the cache. */ void clear(); int size(); /** * Returns a map containing a snapshot of the cache. */ Map<K, V> asMap(); }
5,736
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/UnsafeUtils.java
/* * Copyright 2014-2023 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl; import sun.misc.Unsafe; // NOPMD import java.lang.reflect.Field; /** * Utility class for using {@code sun.misc.Unsafe} to access some internal details to get * better performance. * * <p><b>This class is an internal implementation detail only intended for use within spectator. * It is subject to change without notice.</b></p> */ @SuppressWarnings("PMD") public final class UnsafeUtils { private static final Unsafe UNSAFE; private static final long STRING_VALUE_OFFSET; private static final boolean STRING_VALUE_BYTES; static { Unsafe instance; try { final Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe"); theUnsafe.setAccessible(true); instance = (Unsafe) theUnsafe.get(null); } catch (Exception e) { instance = null; } UNSAFE = instance; if (UNSAFE != null) { long stringValueOffset; boolean stringValueBytes; try { final Field value = String.class.getDeclaredField("value"); stringValueOffset = UNSAFE.objectFieldOffset(value); Object obj = UNSAFE.getObject("value", stringValueOffset); stringValueBytes = obj instanceof byte[]; } catch (Exception e) { stringValueOffset = -1L; stringValueBytes = false; } STRING_VALUE_OFFSET = stringValueOffset; STRING_VALUE_BYTES = stringValueBytes; } else { STRING_VALUE_OFFSET = -1L; STRING_VALUE_BYTES = false; } } private UnsafeUtils() { } /** * Returns true if unsafe operations are supported. Code should have a fallback that * works when it is not available. */ public static boolean supported() { return UNSAFE != null; } /** Returns true if extracting the underlying value array for a String is supported. */ public static boolean stringValueSupported() { return STRING_VALUE_OFFSET > 0L; } /** Returns true if it is a newer JDK that uses a byte array for the characters. */ public static boolean stringValueBytes() { return STRING_VALUE_BYTES; } /** Get the value array for a String as an array of bytes. */ public static byte[] getStringValueBytes(String str) { return (byte[]) UNSAFE.getObject(str, STRING_VALUE_OFFSET); } /** Get the value array for a String as an array of characters. */ public static char[] getStringValueChars(String str) { return (char[]) UNSAFE.getObject(str, STRING_VALUE_OFFSET); } /** Treat a seq of 8 bytes at the given offset as a long value. */ public static long getLong(byte[] bytes, int offset) { long idx = Unsafe.ARRAY_BYTE_BASE_OFFSET + offset; return UNSAFE.getLong(bytes, idx); } }
5,737
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/StreamHelper.java
/* * Copyright 2014-2023 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl; import java.io.ByteArrayOutputStream; /** * Caches ByteArrayOutputStream objects in a thread local to allow for reuse. This can be * useful to reduce the allocations for growing the buffer. It will hold onto the streams * so it should only be used for use-cases where the data written to the stream is bounded. * * <p><b>This class is an internal implementation detail only intended for use within spectator. * It is subject to change without notice.</b></p> */ public final class StreamHelper { private final ThreadLocal<ByteArrayOutputStream> streams; public StreamHelper() { streams = new ThreadLocal<>(); } public ByteArrayOutputStream getOrCreateStream() { ByteArrayOutputStream baos = streams.get(); if (baos == null) { baos = new ByteArrayOutputStream(); streams.set(baos); } else { baos.reset(); } return baos; } }
5,738
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/Config.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl; import com.netflix.spectator.api.RegistryConfig; /** * Helper methods for accessing configuration settings. * * <p><b>This class is an internal implementation detail only intended for use within spectator. * It is subject to change without notice.</b></p> */ public final class Config { private static final String PREFIX = "spectator.api."; private static final RegistryConfig DEFAULT_CONFIG = k -> System.getProperty(PREFIX + k); private Config() { } /** * Returns a default implementation of the registry config backed by system properties. */ public static RegistryConfig defaultConfig() { return DEFAULT_CONFIG; } }
5,739
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/PatternMatcher.java
/* * Copyright 2014-2023 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl; import com.netflix.spectator.impl.matcher.PatternUtils; import java.util.Collections; import java.util.List; import java.util.SortedSet; /** * Efficient alternative to using {@link java.util.regex.Pattern} for use cases that just * require basic matching. Calling the matches method should be mostly equivalent to calling * {@link java.util.regex.Matcher#find()}. It supports most common capabilities of the normal * java regular expressions. Unsupported features are: * * <ul> * <li>Boundary matchers other than {@code ^} and {@code $}</li> * <li>Predefined horizontal and veritical whitespace classes</li> * <li>java.lang.Character classes</li> * <li>Unicode classes</li> * <li>Back references</li> * <li>Special constructs other than lookahead</li> * </ul> * * <p><b>This class is an internal implementation detail only intended for use within spectator. * It is subject to change without notice.</b></p> */ public interface PatternMatcher { /** * Returns true if the passed in string matches the pattern. */ boolean matches(String str); /** * Returns a fixed string prefix for the pattern if one is available. This can be used * with indexed data to help select a subset of values that are possible matches. If the * pattern does not have a fixed string prefix, then null will be returned. */ default String prefix() { return null; } /** * Returns a fixed string that is contained within matching results for the pattern if one * is available. This can be used with indexed data to help select a subset of values that * are possible matches. If the pattern does not have a fixed sub-string, then null will be * returned. */ default String containedString() { return null; } /** * The minimum possible length of a matching string. This can be used as a quick check * to see if there is any way a given string could match. */ default int minLength() { return 0; } /** * Returns true if the pattern is anchored to the start of the string. */ default boolean isStartAnchored() { return false; } /** * Returns true if the pattern is anchored to the end of the string. */ default boolean isEndAnchored() { return false; } /** * Returns true if this matcher will match any string. This can be used as a quick check * to avoid checking for matches. */ default boolean alwaysMatches() { return false; } /** * Returns true if this matcher will not match any string. This can be used as a quick check * to avoid checking for matches. */ default boolean neverMatches() { return false; } /** * Returns true if this matcher is equivalent to performing a starts with check on the * prefix. This can be useful when mapping to storage that may have optimized prefix * matching operators. */ default boolean isPrefixMatcher() { return false; } /** * Returns true if this matcher is equivalent to checking if a string contains a string. * This can be useful when mapping to storage that may have optimized contains matching * operators. */ default boolean isContainsMatcher() { return false; } /** * Returns a set of trigrams for this pattern. A string will only match if it contains * all trigrams in the set. This can be useful for performing an initial filter based on * a trigram index. For complex expressions, expand OR clauses first (see * {@link #expandOrClauses(int)}) and then extract the trigrams for the individual patterns. */ default SortedSet<String> trigrams() { return Collections.emptySortedSet(); } /** * Returns a new matcher that matches the same pattern only ignoring the case of the input * string. Note, character classes will be matched as is and must explicitly include both * cases if that is the desired matching criteria. */ default PatternMatcher ignoreCase() { return this; } /** * Split OR clauses in the pattern to separate matchers. Logically the original pattern * will match if at least one of the patterns in the expanded list matches. * * @param max * Maximum size of the expanded list. This can be used to stop early for some expressions * that may expand to a really large set. * @return * List of expanded patterns or null if this pattern cannot be expanded due to exceeding * the maximum limit. */ default List<PatternMatcher> expandOrClauses(int max) { return Collections.singletonList(this); } /** * Attempts to rewrite this pattern to a set of simple pattern matches that can be combined * with AND, OR, and NOT to have the same matching behavior as the original regex pattern. * This can be useful when working with data stores that have more restricted pattern matching * support such as RE2. * * @param max * Maximum size of the expanded OR list which is needed as part of simplifying the * overall expression. See {@link #expandOrClauses(int)} for more details. * @return * Expression that represents a set of simple pattern matches, or null if it is not * possible to simplify the expression. */ default PatternExpr toPatternExpr(int max) { return null; } /** * Returns a pattern that can be used with a SQL LIKE clause or null if this expression * cannot be expressed as a SQL pattern. Can be used to more optimally map the pattern * to a SQL data store. */ default String toSqlPattern() { return null; } /** * Compile a pattern string and return a matcher that can be used to check if string values * match the pattern. Pattern matchers are can be reused many times and are thread safe. */ static PatternMatcher compile(String pattern) { return PatternUtils.compile(pattern); } /** * Helper function to check if a string value matches the provided pattern. Note, if matching * many values against the same pattern, then it is much more efficient to use * {@link #compile(String)} to get an instance of a matcher that can be reused. * * @param pattern * Pattern to use for creating the matcher instance. * @param value * Value to check against the pattern. * @return * True if the pattern matches the value. */ static boolean matches(String pattern, String value) { return compile(pattern).matches(value); } }
5,740
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/StepDouble.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl; import com.netflix.spectator.api.Clock; import java.util.concurrent.atomic.AtomicLong; /** * Utility class for managing a set of AtomicLong instances mapped to a particular step interval. * The current implementation keeps an array of with two items where one is the current value * being updated and the other is the value from the previous interval and is only available for * polling. * * <p><b>This class is an internal implementation detail only intended for use within spectator. * It is subject to change without notice.</b></p> */ public class StepDouble implements StepValue { private final double init; private final Clock clock; private final long step; private volatile double previous; private final AtomicDouble current; private final AtomicLong lastInitPos; /** Create a new instance. */ public StepDouble(double init, Clock clock, long step) { this.init = init; this.clock = clock; this.step = step; previous = init; current = new AtomicDouble(init); lastInitPos = new AtomicLong(clock.wallTime() / step); } private void rollCount(long now) { final long stepTime = now / step; final long lastInit = lastInitPos.get(); if (lastInit < stepTime && lastInitPos.compareAndSet(lastInit, stepTime)) { final double v = current.getAndSet(init); // Need to check if there was any activity during the previous step interval. If there was // then the init position will move forward by 1, otherwise it will be older. No activity // means the previous interval should be set to the `init` value. previous = (lastInit == stepTime - 1) ? v : init; } } /** Get the AtomicDouble for the current bucket. */ public AtomicDouble getCurrent() { return getCurrent(clock.wallTime()); } /** Get the AtomicDouble for the current bucket. */ public AtomicDouble getCurrent(long now) { rollCount(now); return current; } /** Get the value for the last completed interval. */ public double poll() { return poll(clock.wallTime()); } /** Get the value for the last completed interval. */ public double poll(long now) { rollCount(now); return previous; } /** Get the value for the last completed interval as a rate per second. */ @Override public double pollAsRate() { return pollAsRate(clock.wallTime()); } /** Get the value for the last completed interval as a rate per second. */ @Override public double pollAsRate(long now) { final double amount = poll(now); final double period = step / 1000.0; return amount / period; } /** Get the timestamp for the end of the last completed interval. */ @Override public long timestamp() { return lastInitPos.get() * step; } @Override public String toString() { return "StepDouble{init=" + init + ", previous=" + previous + ", current=" + current.get() + ", lastInitPos=" + lastInitPos.get() + '}'; } }
5,741
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/Hash64.java
/* * Copyright 2014-2023 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl; /** * Helper to compute a 64-bit hash incrementally based on a set of primitives and primitive * arrays. It is currently using the XXH64 algorithm. See the * <a href="https://github.com/Cyan4973/xxHash/blob/dev/doc/xxhash_spec.md">spec</a> for more * details. * * <p><b>This class is an internal implementation detail only intended for use within spectator. * It is subject to change without notice.</b></p> */ @SuppressWarnings("PMD") public final class Hash64 { private static final long PRIME64_1 = 0x9E3779B185EBCA87L; private static final long PRIME64_2 = 0xC2B2AE3D27D4EB4FL; private static final long PRIME64_3 = 0x165667B19E3779F9L; private static final long PRIME64_4 = 0x85EBCA77C2B2AE63L; private static final long PRIME64_5 = 0x27D4EB2F165667C5L; private final long[] stripe; private int stripePos; private int bitPos; private final long seed; private long acc1; private long acc2; private long acc3; private long acc4; private long inputLength; /** Create a new instance with a seed of zero. */ public Hash64() { this(0L); } /** Create a new instance. */ public Hash64(long seed) { this.seed = seed; this.stripe = new long[4]; reset(); } /** Reset so it can be reused for computing another hash. */ public void reset() { stripePos = 0; bitPos = 0; stripe[0] = 0L; acc1 = seed + PRIME64_1 + PRIME64_2; acc2 = seed + PRIME64_2; acc3 = seed; acc4 = seed - PRIME64_1; inputLength = 0L; } private void checkSpace(int size) { // Ensure there is enough space to write the primitive in the current // long value, otherwise move to the next if (size > Long.SIZE - bitPos) { if (++stripePos == stripe.length) { processStripe(); } bitPos = 0; stripe[stripePos] = 0L; } } /** Update the hash with the specified boolean value. */ public Hash64 updateBoolean(boolean value) { return updateByte((byte) (value ? 1 : 0)); } /** Update the hash with the specified boolean values. */ public Hash64 updateBooleans(boolean[] values, int offset, int length) { for (int i = offset; i < offset + length; ++i) { updateBoolean(values[i]); } return this; } /** Update the hash with the specified boolean values. */ public Hash64 updateBooleans(boolean[] values) { return updateBooleans(values, 0, values.length); } /** Update the hash with the specified character value. */ public Hash64 updateChar(char value) { checkSpace(Character.SIZE); final long c = ((long) value) << bitPos; stripe[stripePos] |= c; bitPos += Character.SIZE; return this; } /** Update the hash with the specified character values. */ public Hash64 updateChars(char[] values, int offset, int length) { for (int i = offset; i < offset + length; ++i) { updateChar(values[i]); } return this; } /** Update the hash with the specified character values. */ public Hash64 updateChars(char[] values) { return updateChars(values, 0, values.length); } /** Update the hash with the specified character sequence value. */ public Hash64 updateString(CharSequence str) { if (str instanceof String && UnsafeUtils.stringValueSupported()) { if (UnsafeUtils.stringValueBytes()) { byte[] vs = UnsafeUtils.getStringValueBytes((String) str); updateBytes(vs, 0, vs.length); } else { char[] vs = UnsafeUtils.getStringValueChars((String) str); updateChars(vs, 0, vs.length); } } else { for (int i = 0; i < str.length(); ++i) { updateChar(str.charAt(i)); } } return this; } /** Update the hash with the specified byte value. */ public Hash64 updateByte(byte value) { checkSpace(Byte.SIZE); final long v = ((long) value & 0xFFL) << bitPos; stripe[stripePos] |= v; bitPos += Byte.SIZE; return this; } /** Update the hash with the specified byte values. */ public Hash64 updateBytes(byte[] values, int offset, int length) { if (UnsafeUtils.supported() && length >= 8) { final int bytesInStripe = (Long.SIZE - bitPos) / Byte.SIZE; final int s = offset + bytesInStripe; final int e = s + (length - bytesInStripe) / Long.BYTES * Long.BYTES; // Complete current stripe for (int i = offset; i < s; ++i) { updateByte(values[i]); } // Write long values for (int i = s; i < e; i += Long.BYTES) { updateLong(UnsafeUtils.getLong(values, i)); } // Write remaining bytes for (int i = e; i < offset + length; ++i) { updateByte(values[i]); } } else { for (int i = offset; i < offset + length; ++i) { updateByte(values[i]); } } return this; } /** Update the hash with the specified byte values. */ public Hash64 updateBytes(byte[] values) { return updateBytes(values, 0, values.length); } /** Update the hash with the specified short value. */ public Hash64 updateShort(short value) { checkSpace(Short.SIZE); final long v = ((long) value & 0xFFFFL) << bitPos; stripe[stripePos] |= v; bitPos += Short.SIZE; return this; } /** Update the hash with the specified short values. */ public Hash64 updateShorts(short[] values, int offset, int length) { for (int i = offset; i < offset + length; ++i) { updateShort(values[i]); } return this; } /** Update the hash with the specified short values. */ public Hash64 updateShorts(short[] values) { return updateShorts(values, 0, values.length); } /** Update the hash with the specified int value. */ public Hash64 updateInt(int value) { checkSpace(Integer.SIZE); final long v = ((long) value & 0xFFFFFFFFL) << bitPos; stripe[stripePos] |= v; bitPos += Integer.SIZE; return this; } /** Update the hash with the specified int values. */ public Hash64 updateInts(int[] values, int offset, int length) { for (int i = offset; i < offset + length; ++i) { updateInt(values[i]); } return this; } /** Update the hash with the specified int values. */ public Hash64 updateInts(int[] values) { return updateInts(values, 0, values.length); } /** Update the hash with the specified long value. */ public Hash64 updateLong(long value) { checkSpace(Long.SIZE); stripe[stripePos] = value; bitPos += Long.SIZE; return this; } /** Update the hash with the specified long values. */ public Hash64 updateLongs(long[] values, int offset, int length) { checkSpace(Long.SIZE); // Fill current stripe final int prefixLength = Math.min(length, stripe.length - stripePos); System.arraycopy(values, offset, stripe, stripePos, prefixLength); stripePos += prefixLength; if (stripePos == stripe.length) { processStripe(); } // Copy the remainder, one stripe at a time final int start = offset + prefixLength; final int end = offset + length; for (int i = start; i < end; i += stripe.length) { final int copyLength = Math.min(stripe.length, end - i); System.arraycopy(values, i, stripe, 0, copyLength); stripePos = copyLength; if (stripePos == stripe.length) { processStripe(); } else { stripe[stripePos] = 0L; } } return this; } /** Update the hash with the specified long values. */ public Hash64 updateLongs(long[] values) { return updateLongs(values, 0, values.length); } /** Update the hash with the specified float value. */ public Hash64 updateFloat(float value) { return updateInt(Float.floatToIntBits(value)); } /** Update the hash with the specified float values. */ public Hash64 updateFloats(float[] values, int offset, int length) { for (int i = offset; i < offset + length; ++i) { updateFloat(values[i]); } return this; } /** Update the hash with the specified float values. */ public Hash64 updateFloats(float[] values) { return updateFloats(values, 0, values.length); } /** Update the hash with the specified double value. */ public Hash64 updateDouble(double value) { return updateLong(Double.doubleToLongBits(value)); } /** Update the hash with the specified double values. */ public Hash64 updateDoubles(double[] values, int offset, int length) { for (int i = offset; i < offset + length; ++i) { updateDouble(values[i]); } return this; } /** Update the hash with the specified double values. */ public Hash64 updateDoubles(double[] values) { return updateDoubles(values, 0, values.length); } private void processStripe() { inputLength += 32; acc1 = round(acc1, stripe[0]); acc2 = round(acc2, stripe[1]); acc3 = round(acc3, stripe[2]); acc4 = round(acc4, stripe[3]); stripePos = 0; bitPos = 0; stripe[0] = 0L; } private long round(long acc, long lane) { acc += lane * PRIME64_2; acc = Long.rotateLeft(acc, 31); return acc * PRIME64_1; } private long mergeAccumulator(long acc, long accN) { acc ^= round(0L, accN); acc *= PRIME64_1; return acc + PRIME64_4; } private long consumeRemainingInput(long acc) { for (int i = 0; i < stripePos; ++i) { long lane = stripe[i]; acc ^= round(0, lane); acc = Long.rotateLeft(acc, 27) * PRIME64_1; acc += PRIME64_4; } long buffer = stripe[stripePos]; if (bitPos >= 4) { long lane = buffer & 0xFFFFFFFFL; acc ^= (lane * PRIME64_1); acc = Long.rotateLeft(acc, 23) * PRIME64_2; acc += PRIME64_3; buffer >>>= 32; bitPos -= 4; } while (bitPos >= 1) { long lane = buffer & 0xFFL; acc ^= (lane * PRIME64_5); acc = Long.rotateLeft(acc, 11) * PRIME64_1; buffer >>>= 8; bitPos -= 1; } return acc; } private long avalanche(long acc) { acc ^= acc >>> 33; acc *= PRIME64_2; acc ^= acc >>> 29; acc *= PRIME64_3; acc ^= acc >>> 32; return acc; } /** Compute and return the final hash value. */ public long compute() { // Write final stripe if it is full checkSpace(Byte.SIZE); long acc; if (inputLength < 32L) { // Special case: input is less than 32 bytes acc = seed + PRIME64_5; } else { // Step 3. Accumulator convergence acc = Long.rotateLeft(acc1, 1) + Long.rotateLeft(acc2, 7) + Long.rotateLeft(acc3, 12) + Long.rotateLeft(acc4, 18); acc = mergeAccumulator(acc, acc1); acc = mergeAccumulator(acc, acc2); acc = mergeAccumulator(acc, acc3); acc = mergeAccumulator(acc, acc4); } // Step 4. Add input length inputLength += stripePos * 8L + bitPos / 8L; acc += inputLength; // Step 5. Consume remaining input acc = consumeRemainingInput(acc); // Step 6. Final mix (avalanche) return avalanche(acc); } /** Compute the final hash value and reset the hash accumulator. */ public long computeAndReset() { long h = compute(); reset(); return h; } }
5,742
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/StepValue.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl; /** * Base for {@link StepLong} and {@link StepDouble}. */ public interface StepValue { /** Get the value for the last completed interval as a rate per second. */ double pollAsRate(); /** Get the value for the last completed interval as a rate per second. */ double pollAsRate(long now); /** Get the timestamp for the end of the last completed interval. */ long timestamp(); }
5,743
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/AsciiSet.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl; import java.io.Serializable; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.reflect.Constructor; import java.util.Arrays; import java.util.Optional; /** * Utility class for quickly checking if a string contains only characters contained within * the given set. The set is limited to basic ascii with ranges, if you need more advanced * patterns then regular expressions are a better option though it will likely come with a * steep performance penalty. * * <p><b>This class is an internal implementation detail only intended for use within spectator. * It is subject to change without notice.</b></p> */ @SuppressWarnings("PMD.AvoidAccessibilityAlteration") public final class AsciiSet implements Serializable { private static final long serialVersionUID = 1L; private static boolean isJava8() { String version = System.getProperty("java.version", "1.8"); return version.startsWith("1.8"); } private static final MethodHandle STRING_CONSTRUCTOR; static { if (isJava8()) { MethodHandle handle; try { Constructor<String> ctor = String.class.getDeclaredConstructor(char[].class, boolean.class); ctor.setAccessible(true); handle = MethodHandles.lookup().unreflectConstructor(ctor); } catch (Exception e) { handle = null; } STRING_CONSTRUCTOR = handle; } else { STRING_CONSTRUCTOR = null; } } /** * Creates a new string without copying the buffer if possible. The String class has a * package private constructor that allows the buffer to be shared. */ @SuppressWarnings("PMD.AvoidCatchingThrowable") private static String newString(char[] buf) { if (STRING_CONSTRUCTOR != null) { try { return (String) STRING_CONSTRUCTOR.invokeExact(buf, true); } catch (Throwable t) { // Note: `invokeExact` explicitly throws Throwable to propagate any exception of the // method unchanged. For our purposes we just fallback to the string constructor. return new String(buf); } } else { return new String(buf); } } /** * Create a set containing ascii characters using a simple pattern. The pattern is similar * to a character set in regex. For example, {@code ABC} would contain the characters * {@code A}, {@code B}, and {@code C}. Ranges are supported so all uppercase letters could * be specified as {@code A-Z}. The dash, {@code -}, will be included as part of the set if * it is at the start or end of the pattern. * * @param pattern * String specification of the character set. * @return * Set containing the characters specified in {@code pattern}. */ public static AsciiSet fromPattern(String pattern) { final boolean[] members = new boolean[128]; final int n = pattern.length(); for (int i = 0; i < n; ++i) { final char c = pattern.charAt(i); if (c >= members.length) { throw new IllegalArgumentException("invalid pattern, '" + c + "' is not ascii"); } final boolean isStartOrEnd = i == 0 || i == n - 1; if (isStartOrEnd || c != '-') { members[c] = true; } else { final char s = pattern.charAt(i - 1); final char e = pattern.charAt(i + 1); for (char v = s; v <= e; ++v) { members[v] = true; } } } return new AsciiSet(members); } /** Returns a set that matches no characters. */ public static AsciiSet none() { final boolean[] members = new boolean[128]; return new AsciiSet(members); } /** Returns a set that matches all ascii characters. */ public static AsciiSet all() { final boolean[] members = new boolean[128]; Arrays.fill(members, true); return new AsciiSet(members); } /** Returns a set that matches ascii control characters. */ public static AsciiSet control() { final boolean[] members = new boolean[128]; for (char c = 0; c < members.length; ++c) { members[c] = Character.isISOControl(c); } return new AsciiSet(members); } /** * Converts the members array to a pattern string. Used to provide a user friendly toString * implementation for the set. */ private static String toPattern(boolean[] members) { StringBuilder buf = new StringBuilder(); if (members['-']) { buf.append('-'); } boolean previous = false; char s = 0; for (int i = 0; i < members.length; ++i) { if (members[i] && !previous) { s = (char) i; } else if (!members[i] && previous) { final char e = (char) (i - 1); append(buf, s, e); } previous = members[i]; } if (previous) { final char e = (char) (members.length - 1); append(buf, s, e); } return buf.toString(); } private static void append(StringBuilder buf, char s, char e) { switch (e - s) { case 0: if (s != '-') buf.append(s); break; case 1: buf.append(s).append(e); break; default: buf.append(s).append('-').append(e); break; } } private final String pattern; private final boolean[] members; private AsciiSet(boolean[] members) { this.members = Preconditions.checkNotNull(members, "members array cannot be null"); this.pattern = toPattern(members); } /** * Returns true if the character contained within the set. This is a constant time * operation. */ public boolean contains(char c) { return c < 128 && members[c]; } /** * Returns true if all characters in the string are contained within the set. */ public boolean containsAll(CharSequence str) { return indexOfNonMember(str) == str.length(); } private int indexOfNonMember(CharSequence str) { final int n = str.length(); for (int i = 0; i < n; ++i) { if (!contains(str.charAt(i))) { return i; } } return n; } /** * Replace all characters in the input string with the replacement character. */ public String replaceNonMembers(String input, char replacement) { if (!contains(replacement)) { throw new IllegalArgumentException(replacement + " is not a member of " + pattern); } int i = indexOfNonMember(input); return i < input.length() ? replaceNonMembersImpl(input, i, replacement) : input; } /** * Returns a new set that will match characters either in the this set or in the * set that is provided. */ public AsciiSet union(AsciiSet set) { final boolean[] unionMembers = new boolean[128]; for (int i = 0; i < unionMembers.length; ++i) { unionMembers[i] = members[i] || set.members[i]; } return new AsciiSet(unionMembers); } /** * Returns a new set that will match characters iff they are included this set and in the * set that is provided. */ public AsciiSet intersection(AsciiSet set) { final boolean[] intersectionMembers = new boolean[128]; for (int i = 0; i < intersectionMembers.length; ++i) { intersectionMembers[i] = members[i] && set.members[i]; } return new AsciiSet(intersectionMembers); } /** * Returns a new set that will match characters iff they are included this set and not in the * set that is provided. */ public AsciiSet diff(AsciiSet set) { final boolean[] diffMembers = new boolean[128]; for (int i = 0; i < diffMembers.length; ++i) { diffMembers[i] = members[i] && !set.members[i]; } return new AsciiSet(diffMembers); } /** * Returns a new set that will match characters that are not included this set. */ public AsciiSet invert() { final boolean[] invertMembers = new boolean[128]; for (int i = 0; i < invertMembers.length; ++i) { invertMembers[i] = !members[i]; } return new AsciiSet(invertMembers); } private String replaceNonMembersImpl(String input, int start, char replacement) { final int n = input.length(); final char[] buf = input.toCharArray(); buf[start] = replacement; for (int i = start + 1; i < n; ++i) { final char c = input.charAt(i); if (!contains(c)) buf[i] = replacement; } return newString(buf); } /** * If this set matches a single character, then return an optional with that character. * Otherwise return an empty optional. */ public Optional<Character> character() { char c = 0; int count = 0; for (int i = 0; i < members.length; ++i) { if (members[i]) { c = (char) i; ++count; } } return (count == 1) ? Optional.of(c) : Optional.empty(); } /** Returns true if this set is isEmpty. */ public boolean isEmpty() { for (boolean b : members) { if (b) { return false; } } return true; } @Override public String toString() { return pattern; } @Override public int hashCode() { return pattern.hashCode() + 31 * Arrays.hashCode(members); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || !(obj instanceof AsciiSet)) return false; AsciiSet other = (AsciiSet) obj; return pattern.equals(other.pattern) && Arrays.equals(members, other.members); } }
5,744
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/PatternExpr.java
/* * Copyright 2014-2022 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl; import java.util.List; import java.util.Objects; import java.util.StringJoiner; /** * Represents an expression of simpler patterns combined with AND, OR, and NOT clauses. * This can be used for rewriting complex regular expressions to simpler patterns for * data stores that either support a more limited set of pattern or have better optimizations * in place for simpler operations like starts with or contains. */ public interface PatternExpr { /** * Returns true if the expression matches the value. This is a helper mostly used for testing * to ensure the matching logic is consistent with the original regular expression. */ boolean matches(String value); /** * Convert this expression into a query string. A common example would be to implement * an encoder that would convert it into part of a WHERE clause for a SQL DB. */ default String toQueryString(Encoder encoder) { StringBuilder builder = new StringBuilder(); buildQueryString(encoder, builder); return builder.toString(); } /** * Convert this expression into a query string. A common example would be to implement * an encoder that would convert it into part of a WHERE clause for a SQL DB. */ default void buildQueryString(Encoder encoder, StringBuilder builder) { if (this instanceof Regex) { Regex re = (Regex) this; builder.append(encoder.regex(re.matcher())); } else if (this instanceof And) { List<PatternExpr> exprs = ((And) this).exprs(); int size = exprs.size(); if (size == 1) { exprs.get(0).buildQueryString(encoder, builder); } else if (size > 1) { builder.append(encoder.startAnd()); exprs.get(0).buildQueryString(encoder, builder); for (int i = 1; i < size; ++i) { builder.append(encoder.separatorAnd()); exprs.get(i).buildQueryString(encoder, builder); } builder.append(encoder.endAnd()); } } else if (this instanceof Or) { List<PatternExpr> exprs = ((Or) this).exprs(); int size = exprs.size(); if (size == 1) { exprs.get(0).buildQueryString(encoder, builder); } else if (size > 1) { builder.append(encoder.startOr()); exprs.get(0).buildQueryString(encoder, builder); for (int i = 1; i < size; ++i) { builder.append(encoder.separatorOr()); exprs.get(i).buildQueryString(encoder, builder); } builder.append(encoder.endOr()); } } else if (this instanceof Not) { builder.append(encoder.startNot()); ((Not) this).expr().buildQueryString(encoder, builder); builder.append(encoder.endNot()); } } /** * Encoder to map a pattern expression to an expression for some other language. */ interface Encoder { /** Encode a simple pattern match. */ String regex(PatternMatcher matcher); /** Encode the start for a chain of clauses combined with AND. */ String startAnd(); /** Encode the separator for a chain of clauses combined with AND. */ String separatorAnd(); /** Encode the end for a chain of clauses combined with AND. */ String endAnd(); /** Encode the start for a chain of clauses combined with OR. */ String startOr(); /** Encode the separator for a chain of clauses combined with OR. */ String separatorOr(); /** Encode the end for a chain of clauses combined with OR. */ String endOr(); /** Encode the start for a NOT clause. */ String startNot(); /** Encode the end for a NOT clause. */ String endNot(); } /** A simple expression that performs a single pattern match. */ static PatternExpr simple(PatternMatcher matcher) { return new Regex(matcher); } /** An expression that performs a logical AND of the listed sub-expressions. */ static PatternExpr and(List<PatternExpr> exprs) { if (exprs == null) return null; int size = exprs.size(); Preconditions.checkArg(size > 0, "exprs list cannot be empty"); return size == 1 ? exprs.get(0) : new And(exprs); } /** An expression that performs a logical OR of the listed sub-expressions. */ static PatternExpr or(List<PatternExpr> exprs) { if (exprs == null) return null; int size = exprs.size(); Preconditions.checkArg(size > 0, "exprs list cannot be empty"); return size == 1 ? exprs.get(0) : new Or(exprs); } /** An expression that inverts the match of the sub-expression. */ static PatternExpr not(PatternExpr expr) { return new Not(expr); } final class Regex implements PatternExpr { private final PatternMatcher matcher; Regex(PatternMatcher matcher) { this.matcher = Preconditions.checkNotNull(matcher, "matcher"); } public PatternMatcher matcher() { return matcher; } @Override public boolean matches(String str) { return matcher.matches(str); } @Override public String toString() { return "'" + matcher + "'"; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Regex)) return false; Regex regex = (Regex) o; return matcher.equals(regex.matcher); } @Override public int hashCode() { return Objects.hash(matcher); } } final class And implements PatternExpr { private final List<PatternExpr> exprs; And(List<PatternExpr> exprs) { this.exprs = Preconditions.checkNotNull(exprs, "exprs"); } public List<PatternExpr> exprs() { return exprs; } @Override public boolean matches(String str) { for (PatternExpr expr : exprs) { if (!expr.matches(str)) { return false; } } return true; } @Override public String toString() { StringJoiner joiner = new StringJoiner(" AND ", "(", ")"); exprs.forEach(expr -> joiner.add(expr.toString())); return joiner.toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof And)) return false; And and = (And) o; return exprs.equals(and.exprs); } @Override public int hashCode() { return Objects.hash(exprs); } } final class Or implements PatternExpr { private final List<PatternExpr> exprs; Or(List<PatternExpr> exprs) { this.exprs = Preconditions.checkNotNull(exprs, "exprs"); } public List<PatternExpr> exprs() { return exprs; } @Override public boolean matches(String str) { for (PatternExpr expr : exprs) { if (expr.matches(str)) { return true; } } return false; } @Override public String toString() { StringJoiner joiner = new StringJoiner(" OR ", "(", ")"); exprs.forEach(expr -> joiner.add(expr.toString())); return joiner.toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Or)) return false; Or or = (Or) o; return exprs.equals(or.exprs); } @Override public int hashCode() { return Objects.hash(exprs); } } final class Not implements PatternExpr { private final PatternExpr expr; Not(PatternExpr expr) { this.expr = Preconditions.checkNotNull(expr, "expr"); } public PatternExpr expr() { return expr; } @Override public boolean matches(String str) { return !expr.matches(str); } @Override public String toString() { return "NOT " + expr; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Not)) return false; Not not = (Not) o; return expr.equals(not.expr); } @Override public int hashCode() { return Objects.hash(expr); } } }
5,745
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/package-info.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ /** * Classes in this package are only intended for use internally within spectator. They may change * at any time and without notice. */ package com.netflix.spectator.impl;
5,746
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/Matcher.java
/* * Copyright 2014-2022 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl.matcher; import com.netflix.spectator.impl.PatternExpr; import com.netflix.spectator.impl.PatternMatcher; import java.util.ArrayList; import java.util.List; import java.util.function.Function; /** * Internal interface for matcher implementations. Provides some additional methods * that are not exposed on the public {@link PatternMatcher} interface. */ interface Matcher extends PatternMatcher { /** * Check if a string matches the pattern. * * @param str * Input string to check. * @param start * Starting position in the string to use when checking for a match. * @param length * Maximum length after the starting position to consider when checking for a * match. * @return * If there is a match, then the returned value will be the position in the * string just after the match. Otherwise {@link Constants#NO_MATCH} will be * returned. */ int matches(String str, int start, int length); @Override default boolean matches(String str) { return matches(str, 0, str.length()) >= 0; } @Override default PatternMatcher ignoreCase() { Matcher m = rewrite(PatternUtils::ignoreCase); return new IgnoreCaseMatcher(m); } @SuppressWarnings("PMD.ReturnEmptyCollectionRatherThanNull") @Override default List<PatternMatcher> expandOrClauses(int max) { List<Matcher> ms = PatternUtils.expandOrClauses(this, max); if (ms == null) return null; List<PatternMatcher> results = new ArrayList<>(ms.size()); for (Matcher m : ms) { results.add(Optimizer.optimize(m)); } return results; } @Override default PatternExpr toPatternExpr(int max) { return PatternUtils.toPatternExpr(this, max); } @Override default String toSqlPattern() { return PatternUtils.toSqlPattern(this); } /** Cast the matcher to type {@code T}. */ @SuppressWarnings("unchecked") default <T> T as() { return (T) this; } /** * Return a new matcher by recursively applying the rewrite function to all sub-matchers. */ default Matcher rewrite(Function<Matcher, Matcher> f) { return f.apply(this); } /** * Return a new matcher by recursively applying the rewrite function to all sub-matchers in * the final position of the sequence. */ default Matcher rewriteEnd(Function<Matcher, Matcher> f) { return f.apply(this); } }
5,747
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/Parser.java
/* * Copyright 2014-2022 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl.matcher; import com.netflix.spectator.impl.AsciiSet; import java.util.ArrayList; import java.util.List; import java.util.function.IntPredicate; /** * Parses a pattern into a {@link Matcher} object. */ class Parser { private static final AsciiSet META = AsciiSet.fromPattern("?*+"); private final String tokens; private int current; /** Create a new instance. */ Parser(String tokens) { this.tokens = tokens; this.current = 0; } private IllegalArgumentException error(String message) { return PatternUtils.error(message, tokens, current); } private UnsupportedOperationException unsupported(String message) { return PatternUtils.unsupported(message, tokens, current); } /** Return the matcher for the top level expression. */ Matcher parse() { Matcher m = expr(); if (!isAtEnd()) { throw error("unmatched closing parenthesis"); } return m; } private Matcher expr() { List<Matcher> matchers = new ArrayList<>(); matchers.add(term()); while (!isAtEnd() && peek() != ')' && peek() == '|') { advance(); matchers.add(term()); } if (!isAtEnd() && peek() == ')') { advance(); } return OrMatcher.create(matchers); } private Matcher term() { List<Matcher> matchers = new ArrayList<>(); while (!isAtEnd() && peek() != ')' && peek() != '|') { char c = advance(); switch (c) { case '\\': matchers.add(escape()); break; case '^': matchers.add(StartMatcher.INSTANCE); break; case '$': matchers.add(EndMatcher.INSTANCE); break; case '[': matchers.add(new CharClassMatcher(charClass())); break; case '(': matchers.add(group()); break; case '{': matchers.add(repeat(pop(matchers))); break; case '.': matchers.add(AnyMatcher.INSTANCE); break; case '?': case '*': case '+': if (matchers.isEmpty()) { throw error("dangling modifier"); } matchers.add(meta(pop(matchers))); break; default: matchers.add(new CharSeqMatcher(c)); break; } } return SeqMatcher.create(matchers); } private Matcher pop(List<Matcher> matchers) { return matchers.remove(matchers.size() - 1); } private Matcher escape() { char c = peek(); if (c == 'Q') { return quotation(); } else if (c == 'c') { throw unsupported("control character"); } else if (Constants.DIGIT.contains(c) || c == 'k') { throw unsupported("back references"); } else { AsciiSet set = namedCharClass(); if (set == null) { advance(); return new CharSeqMatcher(String.valueOf(c)); } else { return new CharClassMatcher(set); } } } private Matcher quotation() { int start = current + 1; int end = tokens.indexOf("\\E", start); if (end == -1) { throw error("unclosed quotation"); } current = end + 2; return new CharSeqMatcher(tokens.substring(start, end)); } private Matcher groupExpr() { Matcher m = expr(); if (previous() != ')') { throw error("unclosed group"); } return m; } private Matcher group() { if (peek() == '?') { advance(); char c = advance(); switch (c) { case '<': // Named capturing group advance(v -> v != '>'); if (isAtEnd()) { throw error("unclosed name for capturing group"); } return groupExpr(); case ':': // Non-capturing group return groupExpr(); case '=': return new PositiveLookaheadMatcher(expr()); case '!': return new NegativeLookaheadMatcher(expr()); default: throw unsupported("inline flags"); } } else { return groupExpr(); } } @SuppressWarnings("PMD.ImplicitSwitchFallThrough") private AsciiSet namedCharClass() { boolean invert = false; char c = advance(); switch (c) { case 'd': return Constants.DIGIT; case 'D': return Constants.DIGIT.invert(); case 's': return Constants.SPACE; case 'S': return Constants.SPACE.invert(); case 'w': return Constants.WORD_CHARS; case 'W': return Constants.WORD_CHARS.invert(); case 'h': case 'H': throw unsupported("horizontal whitespace class"); case 'v': case 'V': throw unsupported("vertical whitespace class"); case 'P': invert = true; case 'p': return newNamedCharSet(name(), invert); default: --current; return null; } } private String name() { char c = advance(); if (c == '{') { StringBuilder builder = new StringBuilder(); while (peek() != '}') { builder.append(advance()); } advance(); return builder.toString(); } else { return String.valueOf(c); } } private AsciiSet update(AsciiSet s1, AsciiSet s2, boolean invert) { return invert ? s1.diff(s2) : s1.union(s2); } @SuppressWarnings("PMD") private AsciiSet charClass() { AsciiSet tmp; AsciiSet set = AsciiSet.none(); boolean rangeStart = false; boolean invert = peek() == '^'; if (invert) { advance(); set = AsciiSet.all(); } if (peek() == ']' || peek() == '-') { char c = advance(); set = update(set, AsciiSet.fromPattern(Character.toString(c)), invert); } while (!isAtEnd() && peek() != ']') { char c = advance(); switch (c) { case '[': set = set.union(charClass()); rangeStart = false; break; case '&': if (peek() == '&') { advance(); if (peek() == '[') { advance(); set = set.intersection(charClass()); } else if (peek() != ']') { set = set.intersection(charClass()); --current; } } else { set = update(set, AsciiSet.fromPattern(Character.toString(c)), invert); } rangeStart = false; break; case '\\': tmp = namedCharClass(); if (tmp == null) { c = advance(); rangeStart = true; set = update(set, AsciiSet.fromPattern(Character.toString(c)), invert); } else { rangeStart = false; set = update(set, tmp, invert); } break; case '-': if (rangeStart && peek() != ']') { if (peek() == '\\') { advance(); tmp = namedCharClass(); if (tmp == null) { String range = tokens.subSequence(current - 3, current - 1).toString() + peek(); if (range.endsWith("\\")) { advance(); } set = update(set, AsciiSet.fromPattern(range), invert); } else { set = update(set, AsciiSet.fromPattern("-"), invert); set = update(set, tmp, invert); } } else { String range = tokens.subSequence(current - 2, current + 1).toString(); set = update(set, AsciiSet.fromPattern(range), invert); } } else { set = update(set, AsciiSet.fromPattern("-"), invert); } rangeStart = false; break; default: rangeStart = true; set = update(set, AsciiSet.fromPattern(Character.toString(c)), invert); break; } } if (advance() != ']') { throw error("unclosed character class"); } return set; } private AsciiSet newNamedCharSet(String name, boolean invert) { AsciiSet set = Constants.NAMED_CHAR_CLASSES.get(name); if (set == null) { throw error("unknown character property name: " + name); } return invert ? set.invert() : set; } private Matcher repeat(Matcher matcher) { int start = current; advance(c -> c != '}'); String[] numbers = tokens.subSequence(start, current - 1).toString().split(","); int min = Integer.parseInt(numbers[0]); int max = (numbers.length > 1) ? Integer.parseInt(numbers[1]) : min; if (min < 0) { throw error("illegal repetition, min < 0"); } if (min > max) { throw error("illegal repetition, min > max"); } return new RepeatMatcher(matcher, min, max); } private Matcher meta(Matcher matcher) { int start = current - 1; advance(c -> META.contains((char) c)); --current; String quantifier = tokens.subSequence(start, current).toString(); switch (quantifier) { case "?": // Makes repeat reluctant if (matcher instanceof RepeatMatcher) { return matcher; } case "??": case "?+": return new ZeroOrOneMatcher(matcher, term()); case "*": case "*?": return new ZeroOrMoreMatcher(matcher, term()); case "*+": return new RepeatMatcher(matcher, 0, Integer.MAX_VALUE); case "+": case "+?": return SeqMatcher.create(matcher, new ZeroOrMoreMatcher(matcher, term())); case "++": return SeqMatcher.create(matcher, new RepeatMatcher(matcher, 1, Integer.MAX_VALUE)); default: throw new IllegalArgumentException("unknown quantifier: " + quantifier); } } private boolean isAtEnd() { return current >= tokens.length(); } private char peek() { return tokens.charAt(current); } private char previous() { return tokens.charAt(current - 1); } private char advance() { if (!isAtEnd()) current++; return previous(); } @SuppressWarnings("PMD.AvoidBranchingStatementAsLastInLoop") private void advance(IntPredicate condition) { while (!isAtEnd() && condition.test(advance())) { continue; // loop is just used to advance the position } } }
5,748
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/OrMatcher.java
/* * Copyright 2014-2022 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl.matcher; import com.netflix.spectator.impl.PatternMatcher; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Function; /** Matcher that checks if any of the sub-matchers matchers the string. */ final class OrMatcher implements GreedyMatcher, Serializable { private static final long serialVersionUID = 1L; /** Create a new instance. */ static Matcher create(List<Matcher> matchers) { return create(matchers.toArray(new Matcher[] {})); } /** Create a new instance. */ static Matcher create(Matcher... matchers) { switch (matchers.length) { case 0: return TrueMatcher.INSTANCE; case 1: return matchers[0]; default: return new OrMatcher(matchers); } } private final Matcher[] matchers; private final int minLength; /** Create a new instance. */ OrMatcher(Matcher... matchers) { this.matchers = matchers; int min = Integer.MAX_VALUE; for (PatternMatcher matcher : matchers) { min = Math.min(min, matcher.minLength()); } this.minLength = min; } /** Return the sub-matchers. */ List<Matcher> matchers() { return Arrays.asList(matchers); } @Override public int matches(String str, int start, int length) { for (Matcher matcher : matchers) { int pos = matcher.matches(str, start, length); if (pos >= 0) { return pos; } } return Constants.NO_MATCH; } @Override public int minLength() { return minLength; } @Override public boolean isStartAnchored() { boolean anchored = true; for (Matcher m : matchers) { anchored &= m.isStartAnchored(); } return anchored; } @Override public boolean isEndAnchored() { boolean anchored = true; for (Matcher m : matchers) { anchored &= m.isEndAnchored(); } return anchored; } @Override public Matcher mergeNext(Matcher after) { if (after instanceof TrueMatcher) { return this; } int n = matchers.length; Matcher[] ms = new Matcher[n]; for (int i = 0; i < n; ++i) { ms[i] = SeqMatcher.create(matchers[i], after); } return OrMatcher.create(ms); } @Override public Matcher rewrite(Function<Matcher, Matcher> f) { int n = matchers.length; Matcher[] ms = new Matcher[n]; for (int i = 0; i < n; ++i) { ms[i] = matchers[i].rewrite(f); } return f.apply(OrMatcher.create(ms)); } @Override public Matcher rewriteEnd(Function<Matcher, Matcher> f) { List<Matcher> ms = new ArrayList<>(); for (Matcher m : matchers) { ms.add(m.rewriteEnd(f)); } return f.apply(OrMatcher.create(ms)); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append('('); for (int i = 0; i < matchers.length; ++i) { if (i > 0) { builder.append('|'); } builder.append(matchers[i].toString()); } builder.append(')'); return builder.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } OrMatcher orMatcher = (OrMatcher) o; return minLength == orMatcher.minLength && Arrays.equals(matchers, orMatcher.matchers); } @Override public int hashCode() { int result = minLength; result = 31 * result + Arrays.hashCode(matchers); return result; } }
5,749
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/FalseMatcher.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl.matcher; /** Matcher that always returns false. */ enum FalseMatcher implements Matcher { /** Singleton instance. */ INSTANCE; @Override public int matches(String str, int start, int length) { return Constants.NO_MATCH; } @Override public int minLength() { return 0; } @Override public boolean neverMatches() { return true; } @Override public String toString() { // Pattern that can never match, nothing can be after the end return "$."; } }
5,750
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/Optimizer.java
/* * Copyright 2014-2022 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl.matcher; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; /** * Helper functions for performing rewrites on the pattern to help improve the performance * of matching. */ final class Optimizer { // Safety check to avoid an endless loop if there is a bug that the optimizer does not // converge on an optimal solution. private static final int MAX_ITERATIONS = 1000; private Optimizer() { } /** Return a new instance of the matcher that has been optimized. */ static Matcher optimize(Matcher matcher) { Matcher m = matcher; Matcher opt = optimizeSinglePass(m); for (int i = 0; !m.equals(opt) && i < MAX_ITERATIONS; ++i) { m = opt; opt = optimizeSinglePass(m); } return opt; } private static Matcher optimizeSinglePass(Matcher matcher) { return matcher .rewrite(Optimizer::mergeNext) .rewrite(Optimizer::removeTrueInSequence) .rewrite(Optimizer::sequenceWithFalseIsFalse) .rewrite(Optimizer::sequenceWithStuffAfterEndIsFalse) .rewrite(Optimizer::zeroOrMoreFalse) .rewrite(Optimizer::convertEmptyCharClassToFalse) .rewrite(Optimizer::convertSingleCharClassToSeq) .rewrite(Optimizer::removeStartFollowedByMatchAny) .rewrite(Optimizer::removeMatchAnyFollowedByStart) .rewrite(Optimizer::removeMatchAnyFollowedByIndexOf) .rewrite(Optimizer::removeSequentialMatchAny) .rewrite(Optimizer::flattenNestedSequences) .rewrite(Optimizer::flattenNestedOr) .rewrite(Optimizer::dedupOr) .rewrite(Optimizer::removeFalseBranchesFromOr) .rewrite(Optimizer::extractPrefixFromOr) .rewrite(Optimizer::inlineMatchAnyPrecedingOr) .rewrite(Optimizer::startsWithCharSeq) .rewrite(Optimizer::combineCharSeqAfterStartsWith) .rewrite(Optimizer::combineCharSeqAfterIndexOf) .rewrite(Optimizer::combineAdjacentCharSeqs) .rewrite(Optimizer::removeRepeatedStart) .rewrite(Optimizer::combineAdjacentStart) .rewrite(Optimizer::convertRepeatedAnyCharSeqToIndexOf) .rewriteEnd(Optimizer::removeTrailingMatchAny); } /** * For greedy matchers go ahead and include the next portion of the match so it can be * checked as we go along. Since there is no support for capturing the value we can stop * as soon as it is detected there would be a match rather than finding the largest possible * match. */ static Matcher mergeNext(Matcher matcher) { if (matcher instanceof SeqMatcher) { List<Matcher> matchers = matcher.<SeqMatcher>as().matchers(); List<Matcher> ms = new ArrayList<>(); for (int i = 0; i < matchers.size(); ++i) { Matcher m = matchers.get(i); if (m instanceof OrMatcher) { // Don't merge sequential OR clauses if (i + 1 < matchers.size() && matchers.get(i + 1) instanceof OrMatcher) { ms.add(m); } else { List<Matcher> after = matchers.subList(i + 1, matchers.size()); ms.add(m.<GreedyMatcher>as().mergeNext(SeqMatcher.create(after))); break; } } else if (m instanceof GreedyMatcher) { List<Matcher> after = matchers.subList(i + 1, matchers.size()); ms.add(m.<GreedyMatcher>as().mergeNext(SeqMatcher.create(after))); break; } else { ms.add(m); } } return SeqMatcher.create(ms); } return matcher; } /** * The true matcher is sometimes used as a placeholder while parsing. For sequences it isn't * needed and it is faster to leave them out. */ static Matcher removeTrueInSequence(Matcher matcher) { if (matcher instanceof SeqMatcher) { List<Matcher> matchers = matcher.<SeqMatcher>as().matchers(); List<Matcher> ms = new ArrayList<>(); for (Matcher m : matchers) { if (!(m instanceof TrueMatcher)) { ms.add(m); } } return SeqMatcher.create(ms); } return matcher; } /** * If a sequence contains an explicit false matcher then the whole sequence will never match * and can be treated as false. */ static Matcher sequenceWithFalseIsFalse(Matcher matcher) { if (matcher instanceof SeqMatcher) { for (Matcher m : matcher.<SeqMatcher>as().matchers()) { if (m instanceof FalseMatcher) { return FalseMatcher.INSTANCE; } } } return matcher; } /** * If a sequence contains content after an end anchor then it will never be able to match * and can be treated as false. */ static Matcher sequenceWithStuffAfterEndIsFalse(Matcher matcher) { if (matcher instanceof SeqMatcher) { boolean end = false; for (Matcher m : matcher.<SeqMatcher>as().matchers()) { if (m instanceof EndMatcher) { end = true; } else if (end && !m.alwaysMatches()) { return FalseMatcher.INSTANCE; } } } return matcher; } /** * If the match after a repeated pattern is false, then treat the whole match as false. * For example: {@code ".*$." => "$."}. */ static Matcher zeroOrMoreFalse(Matcher matcher) { if (matcher instanceof ZeroOrMoreMatcher) { ZeroOrMoreMatcher zm = matcher.as(); if (zm.repeated() instanceof FalseMatcher || zm.next() instanceof FalseMatcher) { return zm.next(); } } else if (matcher instanceof ZeroOrOneMatcher) { ZeroOrOneMatcher zm = matcher.as(); if (zm.repeated() instanceof FalseMatcher || zm.next() instanceof FalseMatcher) { return zm.next(); } } return matcher; } /** * If a character class is empty, then it will not match anything and can be treated * as false. */ static Matcher convertEmptyCharClassToFalse(Matcher matcher) { if (matcher instanceof CharClassMatcher) { return matcher.<CharClassMatcher>as().set().isEmpty() ? FalseMatcher.INSTANCE : matcher; } return matcher; } /** * If a character class has a single value, then just match that value ({@code "[a]" => "a"}). * This allows other optimizations to merge the value into adjacent matchers to get a larger * prefix or indexOf check. */ static Matcher convertSingleCharClassToSeq(Matcher matcher) { if (matcher instanceof CharClassMatcher) { Optional<Character> opt = matcher.<CharClassMatcher>as().set().character(); if (opt.isPresent()) { return new CharSeqMatcher(opt.get()); } } return matcher; } /** * If a start anchor is followed by a repeated any match, then the start anchor can be removed * as it will not change the result ({@code "^.*" => ".*"}). */ static Matcher removeStartFollowedByMatchAny(Matcher matcher) { if (matcher instanceof SeqMatcher) { List<Matcher> matchers = matcher.<SeqMatcher>as().matchers(); if (matchers.size() == 2 && matchers.get(0) instanceof StartMatcher && matchers.get(1) instanceof ZeroOrMoreMatcher) { ZeroOrMoreMatcher zm = matchers.get(1).as(); if (zm.repeated() instanceof AnyMatcher) { return zm; } } } return matcher; } /** * If a start anchor is preceded by a repeated any match, then the any match can be removed * as it must be empty for the start anchor to match ({@code ".*^" => "^"}). */ static Matcher removeMatchAnyFollowedByStart(Matcher matcher) { if (matcher instanceof ZeroOrMoreMatcher) { ZeroOrMoreMatcher zm = matcher.as(); if (zm.repeated() instanceof AnyMatcher && zm.next() instanceof SeqMatcher && zm.next().<SeqMatcher>as().matchers().get(0).isStartAnchored()) { return zm.next(); } } return matcher; } /** * Adjacent any matches can be consolidated, e.g., ({@code ".*(.*foo)" => ".*foo"}). */ static Matcher removeMatchAnyFollowedByIndexOf(Matcher matcher) { if (matcher instanceof ZeroOrMoreMatcher) { ZeroOrMoreMatcher zm = matcher.as(); if (zm.repeated() instanceof AnyMatcher && PatternUtils.getPrefix(zm.next()) instanceof IndexOfMatcher) { return zm.next(); } } return matcher; } /** * Remove match any pattern at the end, e.g., ({@code "foo.*$" => "foo"}). */ static Matcher removeTrailingMatchAny(Matcher matcher) { if (matcher instanceof ZeroOrMoreMatcher) { ZeroOrMoreMatcher zm = matcher.as(); boolean atEnd = zm.next() instanceof TrueMatcher || zm.next() instanceof EndMatcher; if (atEnd && zm.repeated() instanceof AnyMatcher) { return TrueMatcher.INSTANCE; } } return matcher; } /** * Adjacent any matches can be consolidated, e.g., ({@code ".*.*" => ".*"}). */ static Matcher removeSequentialMatchAny(Matcher matcher) { if (matcher instanceof ZeroOrMoreMatcher) { ZeroOrMoreMatcher zm1 = matcher.as(); if (zm1.repeated() instanceof AnyMatcher && zm1.next() instanceof ZeroOrMoreMatcher) { ZeroOrMoreMatcher zm2 = zm1.next().as(); if (zm2.repeated() instanceof AnyMatcher) { return zm2; } } } return matcher; } /** * Since we do not need to capture the contents, nested sequences can be simplified to * a just a simple sequence. For example, {@code "a(b.*c)d" => "ab.*cd"}. */ static Matcher flattenNestedSequences(Matcher matcher) { if (matcher instanceof SeqMatcher) { List<Matcher> matchers = matcher.<SeqMatcher>as().matchers(); List<Matcher> ms = new ArrayList<>(); for (Matcher m : matchers) { if (m instanceof SeqMatcher) { ms.addAll(m.<SeqMatcher>as().matchers()); } else { ms.add(m); } } return SeqMatcher.create(ms); } return matcher; } /** * Nested OR clauses can be simplified to a just a simple set of options. For example, * {@code "(a|b|(c|d|(e|f))|g)" => "a|b|c|d|e|f|g"}. */ static Matcher flattenNestedOr(Matcher matcher) { if (matcher instanceof OrMatcher) { List<Matcher> matchers = matcher.<OrMatcher>as().matchers(); List<Matcher> ms = new ArrayList<>(); for (Matcher m : matchers) { if (m instanceof OrMatcher) { ms.addAll(m.<OrMatcher>as().matchers()); } else { ms.add(m); } } return OrMatcher.create(ms); } return matcher; } /** * Remove duplicate branches in an OR clause. For example: {@code "a|b|a" => "a|b"}. */ static Matcher dedupOr(Matcher matcher) { if (matcher instanceof OrMatcher) { List<Matcher> ms = new ArrayList<>( new LinkedHashSet<>(matcher.<OrMatcher>as().matchers())); return OrMatcher.create(ms); } return matcher; } /** * Remove branches that are false from the OR clause. For example: {@code "a|$b|c" => "a|c"}. */ static Matcher removeFalseBranchesFromOr(Matcher matcher) { if (matcher instanceof OrMatcher) { List<Matcher> ms = matcher.<OrMatcher>as() .matchers() .stream() .filter(m -> !(m instanceof FalseMatcher)) .collect(Collectors.toList()); return OrMatcher.create(ms); } return matcher; } /** * Extract common prefix from OR clause. This is beneficial because it reduces the amount * that needs to be checked for each branch. For example: {@code "ab|ac" => "a(b|c)"}. */ static Matcher extractPrefixFromOr(Matcher matcher) { if (matcher instanceof OrMatcher) { // Get the prefix for the first condition List<Matcher> matchers = matcher.<OrMatcher>as().matchers(); if (matchers.isEmpty()) { return matcher; } Matcher prefix = PatternUtils.getPrefix(matchers.get(0)); if (prefix.alwaysMatches()) { return matcher; } List<Matcher> ms = new ArrayList<>(); ms.add(PatternUtils.getSuffix(matchers.get(0))); // Verify all OR conditions have the same prefix for (Matcher m : matchers.subList(1, matchers.size())) { Matcher p = PatternUtils.getPrefix(m); if (!prefix.equals(p)) { return matcher; } ms.add(PatternUtils.getSuffix(m)); } return SeqMatcher.create(prefix, OrMatcher.create(ms)); } return matcher; } /** * If the matcher preceding an OR clause is a repeated any match, move into each branch * of the OR clause. This allows for other optimizations such as conversion to an indexOf * to take effect for each branch. */ static Matcher inlineMatchAnyPrecedingOr(Matcher matcher) { if (matcher instanceof ZeroOrMoreMatcher) { ZeroOrMoreMatcher zm = matcher.as(); if (zm.repeated() instanceof AnyMatcher && zm.next() instanceof OrMatcher) { List<Matcher> matchers = zm.next().<OrMatcher>as().matchers(); List<Matcher> ms = new ArrayList<>(); for (Matcher m : matchers) { ms.add(new ZeroOrMoreMatcher(AnyMatcher.INSTANCE, m)); } return OrMatcher.create(ms); } } return matcher; } /** * If the matcher has a start anchored character sequence, then replace it with a * StartsWithMatcher. In a tight loop this is much faster than a running with a sequence * of two matchers. */ static Matcher startsWithCharSeq(Matcher matcher) { if (matcher instanceof SeqMatcher) { List<Matcher> matchers = matcher.<SeqMatcher>as().matchers(); if (matchers.size() >= 2 && matchers.get(0) instanceof StartMatcher && matchers.get(1) instanceof CharSeqMatcher) { List<Matcher> ms = new ArrayList<>(); ms.add(new StartsWithMatcher(matchers.get(1).<CharSeqMatcher>as().pattern())); ms.addAll(matchers.subList(2, matchers.size())); return SeqMatcher.create(ms); } } return matcher; } /** * If a char sequence is adjacent to a starts with matcher, then append the sequence to * the prefix pattern of the starts with matcher. */ static Matcher combineCharSeqAfterStartsWith(Matcher matcher) { if (matcher instanceof SeqMatcher) { List<Matcher> matchers = matcher.<SeqMatcher>as().matchers(); if (matchers.size() >= 2 && matchers.get(0) instanceof StartsWithMatcher && matchers.get(1) instanceof CharSeqMatcher) { List<Matcher> ms = new ArrayList<>(); String prefix = matchers.get(0).<StartsWithMatcher>as().pattern() + matchers.get(1).<CharSeqMatcher>as().pattern(); ms.add(new StartsWithMatcher(prefix)); ms.addAll(matchers.subList(2, matchers.size())); return SeqMatcher.create(ms); } else { return matcher; } } return matcher; } /** * If a char sequence is adjacent to an index of matcher, then append the sequence to * the pattern of the index of matcher. */ static Matcher combineCharSeqAfterIndexOf(Matcher matcher) { if (matcher instanceof IndexOfMatcher) { IndexOfMatcher m = matcher.as(); Matcher next = PatternUtils.head(m.next()); if (next instanceof CharSeqMatcher) { String pattern = m.pattern() + next.<CharSeqMatcher>as().pattern(); return new IndexOfMatcher(pattern, PatternUtils.tail(m.next())); } } return matcher; } /** * If a char sequence is adjacent to another char sequence, then concatenate the sequences. */ static Matcher combineAdjacentCharSeqs(Matcher matcher) { if (matcher instanceof SeqMatcher) { List<Matcher> matchers = matcher.<SeqMatcher>as().matchers(); List<Matcher> ms = new ArrayList<>(); CharSeqMatcher cs1 = null; for (Matcher m : matchers) { if (m instanceof CharSeqMatcher) { if (cs1 == null) { cs1 = m.as(); } else { CharSeqMatcher cs2 = m.as(); cs1 = new CharSeqMatcher(cs1.pattern() + cs2.pattern()); } } else { if (cs1 != null) { ms.add(cs1); cs1 = null; } ms.add(m); } } if (cs1 != null) { ms.add(cs1); } return SeqMatcher.create(ms); } return matcher; } /** * If a char sequence is preceded by a repeated any match, then replace with an * IndexOfMatcher. The index of operation seems to be optimized by the JDK and is * much faster. Example: {@code ".*foo" => indexOf("foo")}. */ static Matcher convertRepeatedAnyCharSeqToIndexOf(Matcher matcher) { if (matcher instanceof ZeroOrMoreMatcher) { ZeroOrMoreMatcher zm1 = matcher.as(); Matcher prefix = PatternUtils.getPrefix(zm1.next()); if (zm1.repeated() instanceof AnyMatcher && prefix instanceof CharSeqMatcher) { String pattern = prefix.<CharSeqMatcher>as().pattern(); Matcher suffix = PatternUtils.getSuffix(zm1.next()); return new IndexOfMatcher(pattern, suffix); } } return matcher; } /** * Zero or more start anchors is the same as not being anchored by the start. */ static Matcher removeRepeatedStart(Matcher matcher) { if (matcher instanceof ZeroOrMoreMatcher) { ZeroOrMoreMatcher zm = matcher.as(); if (zm.repeated() instanceof StartMatcher) { return zm.next(); } } return matcher; } /** * Multiple adjacent start anchors can be reduced to a single start anchor. */ static Matcher combineAdjacentStart(Matcher matcher) { if (matcher instanceof SeqMatcher) { List<Matcher> matchers = matcher.<SeqMatcher>as().matchers(); if (!matchers.isEmpty() && matchers.get(0) instanceof StartMatcher) { List<Matcher> ms = new ArrayList<>(); ms.add(StartMatcher.INSTANCE); int pos = 0; for (Matcher m : matchers) { if (m instanceof StartMatcher) { ++pos; } else { break; } } ms.addAll(matchers.subList(pos, matchers.size())); return SeqMatcher.create(ms); } } return matcher; } }
5,751
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/IndexOfMatcher.java
/* * Copyright 2014-2023 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl.matcher; import java.io.Serializable; import java.util.Objects; import java.util.SortedSet; import java.util.TreeSet; import java.util.function.Function; /** * Matcher that looks for a given substring within the string being matched. */ final class IndexOfMatcher implements GreedyMatcher, Serializable { private static final long serialVersionUID = 1L; private final String pattern; private final Matcher next; private final boolean ignoreCase; /** Create a new instance. */ IndexOfMatcher(String pattern, Matcher next) { this(pattern, next, false); } /** Create a new instance. */ IndexOfMatcher(String pattern, Matcher next, boolean ignoreCase) { this.pattern = pattern; this.next = next; this.ignoreCase = ignoreCase; } /** Sub-string to look for within the string being checked. */ String pattern() { return pattern; } /** Return the matcher for the portion that follows the sub-string. */ Matcher next() { return next; } @Override public String containedString() { return pattern; } @Override public boolean isContainsMatcher() { return next == TrueMatcher.INSTANCE; } @Override public SortedSet<String> trigrams() { SortedSet<String> ts = new TreeSet<>(); ts.addAll(PatternUtils.computeTrigrams(pattern)); ts.addAll(next.trigrams()); return ts; } private int indexOfIgnoreCase(String str, int offset) { final int length = pattern.length(); final int end = (str.length() - length) + 1; for (int i = offset; i < end; ++i) { if (str.regionMatches(true, i, pattern, 0, length)) { return i; } } return -1; } private int indexOf(String str, int offset) { return ignoreCase ? indexOfIgnoreCase(str, offset) : str.indexOf(pattern, offset); } private boolean endsWithIgnoreCase(String str) { final int length = pattern.length(); final int offset = str.length() - length; return str.regionMatches(true, offset, pattern, 0, length); } private boolean endsWith(String str, int offset) { final int remaining = str.length() - offset; final int length = pattern.length(); if (remaining < length) { return false; } return ignoreCase ? endsWithIgnoreCase(str) : str.endsWith(pattern); } @Override public int matches(String str, int start, int length) { if (next == TrueMatcher.INSTANCE) { int pos = indexOf(str, start); return pos >= 0 ? pos + pattern.length() : Constants.NO_MATCH; } else if (next == EndMatcher.INSTANCE) { return endsWith(str, start) ? length : Constants.NO_MATCH; } else { final int end = start + length; final int stop = end - next.minLength(); int pos = start; while (pos >= 0 && pos <= stop) { pos = indexOf(str, pos); if (pos >= 0) { int s = pos + pattern.length(); int p = next.matches(str, s, end - s); if (p >= 0) { return p; } ++pos; } } return Constants.NO_MATCH; } } @Override public int minLength() { return pattern.length() + next.minLength(); } @Override public boolean isEndAnchored() { return next.isEndAnchored(); } @Override public Matcher mergeNext(Matcher after) { if (after instanceof TrueMatcher) { return this; } Matcher m = (next instanceof TrueMatcher) ? after : SeqMatcher.create(next, after); return new IndexOfMatcher(pattern, m); } @Override public Matcher rewrite(Function<Matcher, Matcher> f) { return f.apply(new IndexOfMatcher(pattern, next.rewrite(f))); } @Override public Matcher rewriteEnd(Function<Matcher, Matcher> f) { return f.apply(new IndexOfMatcher(pattern, next.rewriteEnd(f))); } @Override public String toString() { return ".*" + PatternUtils.escape(pattern) + next; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IndexOfMatcher that = (IndexOfMatcher) o; return ignoreCase == that.ignoreCase && Objects.equals(pattern, that.pattern) && Objects.equals(next, that.next); } @Override public int hashCode() { int result = 1; result = 31 * result + pattern.hashCode(); result = 31 * result + next.hashCode(); result = 31 * result + Boolean.hashCode(ignoreCase); return result; } }
5,752
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/NegativeLookaheadMatcher.java
/* * Copyright 2014-2022 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl.matcher; import java.io.Serializable; import java.util.Objects; import java.util.function.Function; /** * Matcher that does a negative lookahead. If the sub-matcher matches, then it will return * no match, otherwise it will return the starting the position. */ final class NegativeLookaheadMatcher implements Matcher, Serializable { private static final long serialVersionUID = 1L; private final Matcher matcher; /** Create a new instance. */ NegativeLookaheadMatcher(Matcher matcher) { this.matcher = matcher; } Matcher matcher() { return matcher; } @Override public int matches(String str, int start, int length) { int pos = matcher.matches(str, start, length); return (pos >= 0) ? Constants.NO_MATCH : start; } @Override public int minLength() { return 0; } @Override public Matcher rewrite(Function<Matcher, Matcher> f) { return f.apply(new NegativeLookaheadMatcher(matcher.rewrite(f))); } @Override public Matcher rewriteEnd(Function<Matcher, Matcher> f) { return f.apply(new NegativeLookaheadMatcher(matcher.rewriteEnd(f))); } @Override public String toString() { return "(?!" + matcher + ")"; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NegativeLookaheadMatcher that = (NegativeLookaheadMatcher) o; return Objects.equals(matcher, that.matcher); } @Override public int hashCode() { int result = 1; result = 31 * result + matcher.hashCode(); return result; } }
5,753
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/IgnoreCaseMatcher.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl.matcher; import com.netflix.spectator.impl.PatternMatcher; import java.io.Serializable; import java.util.Objects; /** Matcher that ignores the case when checking against the input string. */ final class IgnoreCaseMatcher implements PatternMatcher, Serializable { private static final long serialVersionUID = 1L; private final PatternMatcher matcher; /** * Underlying matcher to use for checking the string. It should have already been converted * to match on the lower case version of the string. */ IgnoreCaseMatcher(PatternMatcher matcher) { this.matcher = matcher; } @Override public boolean matches(String str) { return matcher.matches(str); } @Override public String toString() { return "(?i)" + matcher.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IgnoreCaseMatcher that = (IgnoreCaseMatcher) o; return Objects.equals(matcher, that.matcher); } @Override public int hashCode() { int result = 1; result = 31 * result + matcher.hashCode(); return result; } }
5,754
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/StartsWithMatcher.java
/* * Copyright 2014-2023 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl.matcher; import java.io.Serializable; import java.util.Objects; import java.util.SortedSet; /** * Matcher that checks if the string starts with a given character sequence. */ final class StartsWithMatcher implements Matcher, Serializable { private static final long serialVersionUID = 1L; private final String pattern; private final boolean ignoreCase; /** Create a new instance. */ StartsWithMatcher(String pattern) { this(pattern, false); } /** Create a new instance. */ StartsWithMatcher(String pattern, boolean ignoreCase) { this.pattern = pattern; this.ignoreCase = ignoreCase; } /** Pattern to check for at the start of the string. */ String pattern() { return pattern; } @Override public int matches(String str, int start, int length) { boolean matched = ignoreCase ? str.regionMatches(true, 0, pattern, 0, pattern.length()) : str.startsWith(pattern); return matched ? pattern.length() : Constants.NO_MATCH; } @Override public String prefix() { return pattern; } @Override public String containedString() { return pattern; } @Override public boolean isPrefixMatcher() { return true; } @Override public boolean isContainsMatcher() { return true; } @Override public SortedSet<String> trigrams() { return PatternUtils.computeTrigrams(pattern); } @Override public int minLength() { return pattern.length(); } @Override public boolean isStartAnchored() { return true; } @Override public String toString() { return "^" + PatternUtils.escape(pattern); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } StartsWithMatcher that = (StartsWithMatcher) o; return ignoreCase == that.ignoreCase && Objects.equals(pattern, that.pattern); } @Override public int hashCode() { int result = 1; result = 31 * result + pattern.hashCode(); result = 31 * result + Boolean.hashCode(ignoreCase); return result; } }
5,755
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/TrueMatcher.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl.matcher; /** Matcher that always returns true and does not advance the position. */ enum TrueMatcher implements Matcher { /** Singleton instance. */ INSTANCE; @Override public int matches(String str, int start, int length) { return start; } @Override public int minLength() { return 0; } @Override public boolean alwaysMatches() { return true; } @Override public String toString() { return ""; } }
5,756
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/EndMatcher.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl.matcher; /** Matcher that matches if the position is at the end of the input string. */ enum EndMatcher implements Matcher { /** Singleton instance. */ INSTANCE; @Override public int matches(String str, int start, int length) { return (start == str.length()) ? start : Constants.NO_MATCH; } @Override public int minLength() { return 0; } @Override public boolean isEndAnchored() { return true; } @Override public String toString() { return "$"; } }
5,757
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/SeqMatcher.java
/* * Copyright 2014-2023 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl.matcher; import com.netflix.spectator.impl.PatternMatcher; import java.io.Serializable; import java.util.Arrays; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import java.util.function.Function; /** * Matcher that checks a sequence of sub-matchers. */ final class SeqMatcher implements Matcher, Serializable { private static final long serialVersionUID = 1L; /** Create a new instance. */ static Matcher create(List<Matcher> matchers) { return create(matchers.toArray(new Matcher[] {})); } /** Create a new instance. */ static Matcher create(Matcher... matchers) { switch (matchers.length) { case 0: return TrueMatcher.INSTANCE; case 1: return matchers[0]; default: return new SeqMatcher(matchers); } } private final Matcher[] matchers; private final int minLength; /** Create a new instance. */ private SeqMatcher(Matcher... matchers) { this.matchers = matchers; int min = 0; for (Matcher matcher : matchers) { min += matcher.minLength(); } this.minLength = min; } /** Return the sub-matchers for this sequence. */ List<Matcher> matchers() { return Arrays.asList(matchers); } @Override public int matches(String str, int start, int length) { final int end = start + length; int pos = start; for (int i = 0; i < matchers.length && pos >= 0; ++i) { pos = matchers[i].matches(str, pos, end - pos); } return pos; } @Override public String prefix() { return matchers[0].prefix(); } @Override public String containedString() { String str = null; for (Matcher m : matchers) { str = m.containedString(); if (str != null) break; } return str; } @Override public SortedSet<String> trigrams() { SortedSet<String> ts = new TreeSet<>(); for (Matcher m : matchers) { ts.addAll(m.trigrams()); } return ts; } @Override public int minLength() { return minLength; } @Override public boolean isStartAnchored() { return matchers[0].isStartAnchored(); } @Override public boolean isEndAnchored() { return matchers[matchers.length - 1].isEndAnchored(); } @Override public Matcher rewrite(Function<Matcher, Matcher> f) { int n = matchers.length; Matcher[] ms = new Matcher[n]; for (int i = 0; i < n; ++i) { ms[i] = matchers[i].rewrite(f); } return f.apply(SeqMatcher.create(ms)); } @Override public Matcher rewriteEnd(Function<Matcher, Matcher> f) { int n = matchers.length; Matcher[] ms = new Matcher[n]; System.arraycopy(matchers, 0, ms, 0, n - 1); ms[n - 1] = matchers[n - 1].rewriteEnd(f); return f.apply(SeqMatcher.create(ms)); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append('('); for (PatternMatcher m : matchers) { builder.append(m.toString()); } builder.append(')'); return builder.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SeqMatcher that = (SeqMatcher) o; return minLength == that.minLength && Arrays.equals(matchers, that.matchers); } @Override public int hashCode() { int result = minLength; result = 31 * result + Arrays.hashCode(matchers); return result; } }
5,758
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/CharSeqMatcher.java
/* * Copyright 2014-2023 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl.matcher; import java.io.Serializable; import java.util.Objects; import java.util.SortedSet; /** Matcher that checks for a sequence of characters. */ final class CharSeqMatcher implements Matcher, Serializable { private static final long serialVersionUID = 1L; private final String pattern; private final boolean ignoreCase; /** Create a new instance. */ CharSeqMatcher(char pattern) { this(String.valueOf(pattern)); } /** Create a new instance. */ CharSeqMatcher(String pattern) { this(pattern, false); } /** Create a new instance. */ CharSeqMatcher(String pattern, boolean ignoreCase) { this.pattern = pattern; this.ignoreCase = ignoreCase; } /** Sub-string to look for within the string being checked. */ String pattern() { return pattern; } @Override public String containedString() { return pattern; } @Override public SortedSet<String> trigrams() { return PatternUtils.computeTrigrams(pattern); } @Override public int matches(String str, int start, int length) { final int plength = pattern.length(); boolean matched = ignoreCase ? str.regionMatches(true, start, pattern, 0, plength) : str.startsWith(pattern, start); //System.out.println(matched + "::-" + str.substring(start)); return matched ? start + plength : Constants.NO_MATCH; } @Override public int minLength() { return pattern.length(); } @Override public String toString() { return PatternUtils.escape(pattern); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CharSeqMatcher that = (CharSeqMatcher) o; return ignoreCase == that.ignoreCase && Objects.equals(pattern, that.pattern); } @Override public int hashCode() { int result = 1; result = 31 * result + pattern.hashCode(); result = 31 * result + Boolean.hashCode(ignoreCase); return result; } }
5,759
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/StartMatcher.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl.matcher; /** Matcher that matches if the position is at the start of the input string. */ enum StartMatcher implements Matcher { /** Singleton instance. */ INSTANCE; @Override public int matches(String str, int start, int length) { return (start == 0) ? 0 : Constants.NO_MATCH; } @Override public int minLength() { return 0; } @Override public boolean isStartAnchored() { return true; } @Override public String toString() { return "^"; } }
5,760
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/CharClassMatcher.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl.matcher; import com.netflix.spectator.impl.AsciiSet; import java.io.Serializable; import java.util.Objects; /** Matcher that matches any character from a specified set. */ final class CharClassMatcher implements Matcher, Serializable { private static final long serialVersionUID = 1L; private final AsciiSet set; private final boolean ignoreCase; /** Create a new instance. */ CharClassMatcher(AsciiSet set) { this(set, false); } /** Create a new instance. */ CharClassMatcher(AsciiSet set, boolean ignoreCase) { this.set = set; this.ignoreCase = ignoreCase; } /** Set of characters that will match. */ AsciiSet set() { return set; } private char toOtherCase(char c) { final char amount = 'a' - 'A'; if (c >= 'A' && c <= 'Z') { return (char) (c + amount); } else if (c >= 'a' && c <= 'z') { return (char) (c - amount); } else { return c; } } @Override public int matches(String str, int start, int length) { if (length > 0) { char c = str.charAt(start); boolean matched = ignoreCase ? set.contains(c) || set.contains(toOtherCase(c)) : set.contains(c); return matched ? start + 1 : Constants.NO_MATCH; } else { return Constants.NO_MATCH; } } @Override public int minLength() { return 1; } @Override public String toString() { String p = set.toString(); String n = set.invert().toString(); String str = (p.length() < n.length() || n.isEmpty()) ? PatternUtils.escape(p) : "^" + PatternUtils.escape(n); return "[" + str + "]"; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CharClassMatcher that = (CharClassMatcher) o; return ignoreCase == that.ignoreCase && Objects.equals(set, that.set); } @Override public int hashCode() { int result = 1; result = 31 * result + set.hashCode(); result = 31 * result + Boolean.hashCode(ignoreCase); return result; } }
5,761
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/RepeatMatcher.java
/* * Copyright 2014-2023 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl.matcher; import java.io.Serializable; import java.util.Collections; import java.util.Objects; import java.util.SortedSet; import java.util.function.Function; /** Matcher that looks for a fixed number of repetitions. */ final class RepeatMatcher implements Matcher, Serializable { private static final long serialVersionUID = 1L; private final Matcher repeated; private final int min; private final int max; /** Create a new instance. */ RepeatMatcher(Matcher repeated, int min, int max) { this.repeated = repeated; this.min = min; this.max = max; } Matcher repeated() { return repeated; } int min() { return min; } int max() { return max; } @Override public String containedString() { return min == 0 ? null : repeated.containedString(); } @Override public SortedSet<String> trigrams() { return min == 0 ? Collections.emptySortedSet() : repeated.trigrams(); } @Override public int matches(String str, int start, int length) { final int end = start + length; int pos = start; int numMatches = 0; while (pos >= 0 && numMatches < max) { int p = repeated.matches(str, pos, end - pos); if (p >= 0) { ++numMatches; pos = p; } else { return (numMatches >= min) ? pos : Constants.NO_MATCH; } } return pos; } @Override public int minLength() { return min * repeated.minLength(); } @Override public Matcher rewrite(Function<Matcher, Matcher> f) { return new RepeatMatcher(f.apply(repeated), min, max); } @Override public Matcher rewriteEnd(Function<Matcher, Matcher> f) { return new RepeatMatcher(f.apply(repeated), min, max); } @Override public String toString() { return min == max ? "(?:" + repeated + "){" + min + "}" : "(?:" + repeated + "){" + min + "," + max + "}"; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RepeatMatcher that = (RepeatMatcher) o; return min == that.min && max == that.max && Objects.equals(repeated, that.repeated); } @Override public int hashCode() { int result = 1; result = 31 * result + repeated.hashCode(); result = 31 * result + min; result = 31 * result + max; return result; } }
5,762
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/ZeroOrMoreMatcher.java
/* * Copyright 2014-2023 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl.matcher; import com.netflix.spectator.impl.Preconditions; import java.io.Serializable; import java.util.Objects; import java.util.SortedSet; import java.util.function.Function; /** * Matcher that looks for a pattern zero or more times followed by another pattern. */ final class ZeroOrMoreMatcher implements GreedyMatcher, Serializable { private static final long serialVersionUID = 1L; private final Matcher repeated; private final Matcher next; /** Create a new instance. */ ZeroOrMoreMatcher(Matcher repeated, Matcher next) { this.repeated = repeated; this.next = Preconditions.checkNotNull(next, "next"); } /** Return the matcher for the repeated portion. */ Matcher repeated() { return repeated; } /** Return the matcher for the portion that follows the sub-string. */ Matcher next() { return next; } @Override public String containedString() { return next.containedString(); } @Override public SortedSet<String> trigrams() { return next.trigrams(); } @Override public int matches(String str, int start, int length) { final int end = start + length; if (repeated instanceof AnyMatcher) { final int stop = end - next.minLength(); for (int pos = start; pos >= 0 && pos <= stop; ++pos) { int p = next.matches(str, pos, end - pos); if (p >= start) { return p; } } return Constants.NO_MATCH; } else if (next != TrueMatcher.INSTANCE) { final int stop = end - next.minLength(); int pos = start; while (pos >= start && pos <= stop) { int p = next.matches(str, pos, end - pos); if (p >= start) { return p; } // The repeated portion could potentially be an empty string matcher, to avoid an // endless loop we need to ensure that the position has moved forward int tmp = repeated.matches(str, pos, end - pos); if (tmp == pos) { return Constants.NO_MATCH; } pos = tmp; } return Constants.NO_MATCH; } else { int matchPos = Constants.NO_MATCH; int pos = start; while (pos > matchPos) { matchPos = pos; pos = repeated.matches(str, pos, end - pos); } return matchPos; } } @Override public int minLength() { return next.minLength(); } @Override public boolean isEndAnchored() { return next.isEndAnchored(); } @Override public boolean alwaysMatches() { return repeated instanceof AnyMatcher && (next instanceof TrueMatcher || next instanceof EndMatcher); } @Override public Matcher mergeNext(Matcher after) { if (after instanceof TrueMatcher) { return this; } Matcher m = (next instanceof TrueMatcher) ? after : SeqMatcher.create(next, after); return new ZeroOrMoreMatcher(repeated, m); } @Override public Matcher rewrite(Function<Matcher, Matcher> f) { return f.apply(new ZeroOrMoreMatcher(repeated.rewrite(f), next.rewrite(f))); } @Override public Matcher rewriteEnd(Function<Matcher, Matcher> f) { return f.apply(new ZeroOrMoreMatcher(repeated, next.rewriteEnd(f))); } @Override public String toString() { return "(" + repeated + ")*" + (next instanceof TrueMatcher ? "" : next.toString()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ZeroOrMoreMatcher that = (ZeroOrMoreMatcher) o; return Objects.equals(repeated, that.repeated) && Objects.equals(next, that.next); } @Override public int hashCode() { int result = 1; result = 31 * result + repeated.hashCode(); result = 31 * result + next.hashCode(); return result; } }
5,763
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/AnyMatcher.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl.matcher; /** Matcher that matches any character. */ enum AnyMatcher implements Matcher { /** Singleton instance. */ INSTANCE; @Override public int matches(String str, int start, int length) { return (length > 0) ? start + 1 : Constants.NO_MATCH; } @Override public int minLength() { return 1; } @Override public String toString() { return "."; } }
5,764
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/PatternUtils.java
/* * Copyright 2014-2023 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl.matcher; import com.netflix.spectator.impl.PatternExpr; import com.netflix.spectator.impl.PatternMatcher; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import java.util.function.Function; import java.util.stream.Collectors; /** * Helper functions for working with patterns. * * <p><b>This class is an internal implementation detail only intended for use within spectator. * It is subject to change without notice.</b></p> */ public final class PatternUtils { private PatternUtils() { } /** * Compile a pattern string and return a matcher that can be used to check if string values * match the pattern. Pattern matchers are can be reused many times and are thread safe. */ public static PatternMatcher compile(String pattern) { String p = pattern; boolean ignoreCase = false; if (p.startsWith("(?i)")) { ignoreCase = true; p = pattern.substring(4); } if (p.length() > 0) { p = "^.*(" + p + ").*$"; } Parser parser = new Parser(PatternUtils.expandEscapedChars(p)); Matcher m = Optimizer.optimize(parser.parse()); return ignoreCase ? m.ignoreCase() : m; } private static String context(String str, int pos) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < pos; ++i) { builder.append(' '); } builder.append('^'); return str + "\n" + builder.toString(); } /** * Create an IllegalArgumentException with a message including context based * on the position. */ static IllegalArgumentException error(String message, String str, int pos) { return new IllegalArgumentException(message + "\n" + context(str, pos)); } /** * Create an UnsupportedOperationException with a message including context based * on the position. */ static UnsupportedOperationException unsupported(String message, String str, int pos) { return new UnsupportedOperationException(message + "\n" + context(str, pos)); } @SuppressWarnings("PMD.PreserveStackTrace") private static char parse(String num, int radix, String mode, String str, int pos) { try { return (char) Integer.parseInt(num, radix); } catch (NumberFormatException e) { throw error("invalid " + mode + " escape sequence", str, pos); } } /** * Expand escaped characters. Escapes that are needed for structural elements of the * pattern will not be expanded. */ @SuppressWarnings({"PMD.NcssCount", "PMD.AvoidReassigningLoopVariables"}) static String expandEscapedChars(String str) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < str.length(); ++i) { char c = str.charAt(i); if (c == '\\') { ++i; if (i >= str.length()) { throw error("dangling escape", str, i); } c = str.charAt(i); switch (c) { case 't': builder.append('\t'); break; case 'n': builder.append('\n'); break; case 'r': builder.append('\r'); break; case 'f': builder.append('\f'); break; case 'a': builder.append('\u0007'); break; case 'e': builder.append('\u001B'); break; case '0': int numDigits = 0; for (int j = i + 1; j < Math.min(i + 4, str.length()); ++j) { c = str.charAt(j); if (c >= '0' && c <= '7') { ++numDigits; } else { break; } } if (numDigits < 1 || numDigits > 3) { throw error("invalid octal escape sequence", str, i); } c = parse(str.substring(i + 1, i + numDigits + 1), 8, "octal", str, i); builder.append(c); i += numDigits; break; case 'x': if (i + 3 > str.length()) { throw error("invalid hexadecimal escape sequence", str, i); } c = parse(str.substring(i + 1, i + 3), 16, "hexadecimal", str, i); builder.append(c); i += 2; break; case 'u': if (i + 5 > str.length()) { throw error("invalid unicode escape sequence", str, i); } c = parse(str.substring(i + 1, i + 5), 16, "unicode", str, i); builder.append(c); i += 4; break; default: builder.append('\\').append(c); break; } } else { builder.append(c); } } return builder.toString(); } /** * Escape a string so it will be interpreted as a literal character sequence when processed * as a regular expression. */ @SuppressWarnings("PMD.NcssCount") public static String escape(String str) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < str.length(); ++i) { char c = str.charAt(i); switch (c) { case '\t': builder.append("\\t"); break; case '\n': builder.append("\\n"); break; case '\r': builder.append("\\r"); break; case '\f': builder.append("\\f"); break; case '\\': builder.append("\\\\"); break; case '^': builder.append("\\^"); break; case '$': builder.append("\\$"); break; case '.': builder.append("\\."); break; case '?': builder.append("\\?"); break; case '*': builder.append("\\*"); break; case '+': builder.append("\\+"); break; case '[': builder.append("\\["); break; case ']': builder.append("\\]"); break; case '(': builder.append("\\("); break; case ')': builder.append("\\)"); break; case '{': builder.append("\\{"); break; case '}': builder.append("\\}"); break; default: if (c <= ' ' || c > '~') { builder.append(String.format("\\u%04x", (int) c)); } else { builder.append(c); } break; } } return builder.toString(); } /** Convert to a matchers that ignores the case. */ static Matcher ignoreCase(Matcher matcher) { if (matcher instanceof CharClassMatcher) { CharClassMatcher m = matcher.as(); return new CharClassMatcher(m.set(), true); } else if (matcher instanceof CharSeqMatcher) { CharSeqMatcher m = matcher.as(); return new CharSeqMatcher(m.pattern(), true); } else if (matcher instanceof IndexOfMatcher) { IndexOfMatcher m = matcher.as(); return new IndexOfMatcher(m.pattern(), m.next(), true); } else if (matcher instanceof StartsWithMatcher) { StartsWithMatcher m = matcher.as(); return new StartsWithMatcher(m.pattern(), true); } else { return matcher; } } /** * Expand OR clauses in the provided matcher up to the max limit. If expanding would exceed * the max, then null will be returned. */ @SuppressWarnings("PMD.ReturnEmptyCollectionRatherThanNull") static List<Matcher> expandOrClauses(Matcher matcher, int max) { if (matcher instanceof IndexOfMatcher) { IndexOfMatcher m = matcher.as(); return map(expandOrClauses(m.next(), max), n -> new IndexOfMatcher(m.pattern(), n), max); } else if (matcher instanceof ZeroOrMoreMatcher) { ZeroOrMoreMatcher m = matcher.as(); return map(expandOrClauses(m.next(), max), n -> new ZeroOrMoreMatcher(m.repeated(), n), max); } else if (matcher instanceof ZeroOrOneMatcher) { ZeroOrOneMatcher m = matcher.as(); List<Matcher> rs = expandOrClauses(m.repeated(), max); List<Matcher> ns = expandOrClauses(m.next(), max); if (rs == null || ns == null || ns.size() * (rs.size() + 1) > max) { return null; } else if (rs.size() == 1 && ns.size() == 1) { return Collections.singletonList(matcher); } else { List<Matcher> results = new ArrayList<>(ns); for (Matcher r : rs) { for (Matcher n : ns) { results.add(new ZeroOrOneMatcher(r, n)); } } return results; } } else if (matcher instanceof PositiveLookaheadMatcher) { PositiveLookaheadMatcher m = matcher.as(); return map(expandOrClauses(m.matcher(), max), PositiveLookaheadMatcher::new, max); } else if (matcher instanceof SeqMatcher) { return expandSeq(matcher.as(), max); } else if (matcher instanceof OrMatcher) { return expandOr(matcher.as(), max); } else { return Collections.singletonList(matcher); } } @SuppressWarnings("PMD.ReturnEmptyCollectionRatherThanNull") private static List<Matcher> map(List<Matcher> ms, Function<Matcher, Matcher> f, int max) { if (ms == null || ms.size() > max) { return null; } List<Matcher> results = new ArrayList<>(ms.size()); for (Matcher m : ms) { results.add(f.apply(m)); } return results; } @SuppressWarnings("PMD.ReturnEmptyCollectionRatherThanNull") private static List<Matcher> expandSeq(SeqMatcher seqMatcher, int max) { List<List<Matcher>> results = new ArrayList<>(); for (Matcher matcher : seqMatcher.matchers()) { if (results.isEmpty()) { List<Matcher> rs = expandOrClauses(matcher, max); if (rs == null) return null; for (Matcher m : rs) { List<Matcher> tmp = new ArrayList<>(); tmp.add(m); results.add(tmp); } } else { List<Matcher> rs = expandOrClauses(matcher, max); if (rs == null || results.size() * rs.size() > max) return null; List<List<Matcher>> tmp = new ArrayList<>(results.size() * rs.size()); for (List<Matcher> ms : results) { for (Matcher r : rs) { List<Matcher> seq = new ArrayList<>(ms); seq.add(r); tmp.add(seq); } } results = tmp; } } List<Matcher> tmp = new ArrayList<>(results.size()); for (List<Matcher> ms : results) { tmp.add(SeqMatcher.create(ms)); } return tmp; } @SuppressWarnings("PMD.ReturnEmptyCollectionRatherThanNull") private static List<Matcher> expandOr(OrMatcher matcher, int max) { List<Matcher> ms = matcher.matchers(); if (ms.size() > max) { return null; } List<Matcher> results = new ArrayList<>(); for (Matcher m : ms) { List<Matcher> tmp = expandOrClauses(m, max); if (tmp == null || results.size() + tmp.size() > max) { return null; } results.addAll(tmp); } return results; } static PatternExpr toPatternExpr(Matcher matcher, int max) { List<Matcher> matchers = expandOrClauses(matcher, max); if (matchers == null) { return null; } else { List<PatternExpr> exprs = matchers .stream() .map(PatternUtils::expandLookahead) .collect(Collectors.toList()); return PatternExpr.or(exprs); } } private static PatternExpr expandLookahead(Matcher matcher) { List<PatternExpr> exprs = new ArrayList<>(); // 0 - positive matcher to append // 1 - negative matcher to append // 2 - remaining matcher to keep processing Matcher[] results = new Matcher[3]; // Keep processing until no lookaheads remain removeNextLookahead(matcher, results); while (results[2] != null) { if (results[0] != null) exprs.add(PatternExpr.simple(results[0])); if (results[1] != null) exprs.add(PatternExpr.not(PatternExpr.simple(results[1]))); removeNextLookahead(results[2], results); } // If the results array is all null, then something was incompatible, return null // to indicate this regex cannot be simplified if (results[0] == null && results[1] == null) { return null; } // Add final expression if (results[0] != null) exprs.add(PatternExpr.simple(results[0])); if (results[1] != null) exprs.add(PatternExpr.not(PatternExpr.simple(results[1]))); return PatternExpr.and(exprs); } private static void removeNextLookahead(Matcher matcher, Matcher[] results) { Arrays.fill(results, null); rewriteNextLookahead(matcher, results); } @SuppressWarnings("PMD") private static void rewriteNextLookahead(Matcher matcher, Matcher[] results) { if (matcher instanceof IndexOfMatcher) { IndexOfMatcher m = matcher.as(); rewriteNextLookahead(m.next(), results); for (int i = 0; i < results.length; ++i) { if (results[i] != null) { results[i] = new IndexOfMatcher(m.pattern(), results[i]); } } } else if (matcher instanceof SeqMatcher) { SeqMatcher m = matcher.as(); Matcher[] ms = m.matchers().toArray(new Matcher[0]); for (int i = 0; i < ms.length; ++i) { results[0] = null; rewriteNextLookahead(ms[i], results); if (results[2] != null) { // Truncated sequence with lookahead match at the end List<Matcher> matchers = new ArrayList<>(i + 1); matchers.addAll(Arrays.asList(ms).subList(0, i)); if (results[0] != null) { matchers.add(results[0]); results[0] = SeqMatcher.create(matchers); } else { matchers.add(results[1]); results[1] = SeqMatcher.create(matchers); } // Matcher with lookahead removed ms[i] = results[2]; results[2] = SeqMatcher.create(ms); break; } else if (results[0] == null) { // Indicates this entry of the sequence cannot be simplified return; } else { results[0] = m; } } } else if (matcher instanceof ZeroOrMoreMatcher) { ZeroOrMoreMatcher m = matcher.as(); if (containsLookahead(m.repeated())) { return; } removeNextLookahead(m.next(), results); for (int i = 0; i < results.length; ++i) { if (results[i] != null) { results[i] = new ZeroOrMoreMatcher(m.repeated(), results[i]); } } } else if (matcher instanceof ZeroOrOneMatcher) { ZeroOrOneMatcher m = matcher.as(); if (containsLookahead(m.repeated())) { return; } removeNextLookahead(m.next(), results); for (int i = 0; i < results.length; ++i) { if (results[i] != null) { results[i] = new ZeroOrOneMatcher(m.repeated(), results[i]); } } } else if (matcher instanceof RepeatMatcher) { RepeatMatcher m = matcher.as(); if (m.max() > 1000 || containsLookahead(m.repeated())) { // Some engines like RE2 have limitations on the number of repetitions. Treat // those as failures to match to the expression. return; } else { results[0] = matcher; } } else if (matcher instanceof PositiveLookaheadMatcher) { PositiveLookaheadMatcher m = matcher.as(); if (containsLookahead(m.matcher())) { return; } results[0] = m.matcher(); results[2] = TrueMatcher.INSTANCE; } else if (matcher instanceof NegativeLookaheadMatcher) { NegativeLookaheadMatcher m = matcher.as(); if (containsLookahead(m.matcher())) { return; } results[1] = m.matcher(); results[2] = TrueMatcher.INSTANCE; } else if (!containsLookahead(matcher)) { results[0] = matcher; } for (int i = 0; i < results.length; ++i) { if (results[i] != null) { results[i] = Optimizer.optimize(results[i]); } } } private static boolean containsLookahead(Matcher matcher) { if (matcher instanceof NegativeLookaheadMatcher) { return true; } else if (matcher instanceof PositiveLookaheadMatcher) { return true; } else if (matcher instanceof IndexOfMatcher) { IndexOfMatcher m = matcher.as(); return containsLookahead(m.next()); } else if (matcher instanceof OrMatcher) { for (Matcher m : matcher.<OrMatcher>as().matchers()) { if (containsLookahead(m)) { return true; } } return false; } else if (matcher instanceof RepeatMatcher) { RepeatMatcher m = matcher.as(); return containsLookahead(m.repeated()); } else if (matcher instanceof SeqMatcher) { for (Matcher m : matcher.<SeqMatcher>as().matchers()) { if (containsLookahead(m)) { return true; } } return false; } else if (matcher instanceof ZeroOrMoreMatcher) { ZeroOrMoreMatcher m = matcher.as(); return containsLookahead(m.repeated()) || containsLookahead(m.next()); } else if (matcher instanceof ZeroOrOneMatcher) { ZeroOrOneMatcher m = matcher.as(); return containsLookahead(m.repeated()) || containsLookahead(m.next()); } else { return false; } } /** Convert a matcher to a SQL pattern or return null if not possible. */ static String toSqlPattern(Matcher matcher) { StringBuilder builder = new StringBuilder(); if (toSqlPattern(builder, matcher)) { if (!endsWithWildcard(builder) && !matcher.isEndAnchored()) { builder.append('%'); } return builder.toString(); } else { return null; } } private static boolean endsWithWildcard(StringBuilder builder) { int n = builder.length(); return n > 0 && builder.charAt(n - 1) == '%'; } private static String sqlEscape(String str) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < str.length(); ++i) { char c = str.charAt(i); switch (c) { case '_': builder.append("\\_"); break; case '%': builder.append("\\%"); break; case '\\': builder.append("\\\\"); break; default: builder.append(c); break; } } return builder.toString(); } private static boolean toSqlPattern(StringBuilder builder, Matcher matcher) { if (matcher instanceof TrueMatcher) { builder.append("%"); return true; } else if (matcher instanceof AnyMatcher) { builder.append('_'); return true; } else if (matcher instanceof StartMatcher || matcher instanceof EndMatcher) { return true; } else if (matcher instanceof ZeroOrMoreMatcher) { ZeroOrMoreMatcher m = matcher.as(); if (m.repeated() == AnyMatcher.INSTANCE) { builder.append('%'); return toSqlPattern(builder, m.next()); } } else if (matcher instanceof SeqMatcher) { SeqMatcher sm = matcher.as(); for (Matcher m : sm.matchers()) { if (!toSqlPattern(builder, m)) { return false; } } return true; } else if (matcher instanceof CharSeqMatcher) { CharSeqMatcher m = matcher.as(); builder.append(sqlEscape(m.pattern())); return true; } else if (matcher instanceof IndexOfMatcher) { IndexOfMatcher m = matcher.as(); builder.append('%').append(sqlEscape(m.pattern())); return toSqlPattern(builder, m.next()); } else if (matcher instanceof StartsWithMatcher) { StartsWithMatcher m = matcher.as(); builder.append(sqlEscape(m.pattern())); return true; } return false; } /** Returns the first matcher from a sequence. */ static Matcher head(Matcher matcher) { if (matcher instanceof SeqMatcher) { List<Matcher> ms = matcher.<SeqMatcher>as().matchers(); return ms.get(0); } else { return matcher; } } /** * Returns all but the first matcher from a sequence or True if there is only a single * matcher in the sequence. */ static Matcher tail(Matcher matcher) { if (matcher instanceof SeqMatcher) { List<Matcher> ms = matcher.<SeqMatcher>as().matchers(); return SeqMatcher.create(ms.subList(1, ms.size())); } else { return TrueMatcher.INSTANCE; } } /** * Get the prefix matcher. This is similar to {@link #head(Matcher)} except that it can * reach into character sequences as well as higher level sequences. */ static Matcher getPrefix(Matcher matcher) { if (matcher instanceof SeqMatcher) { List<Matcher> ms = matcher.<SeqMatcher>as().matchers(); return ms.get(0); } else if (matcher instanceof ZeroOrMoreMatcher) { ZeroOrMoreMatcher zm = matcher.as(); return new ZeroOrMoreMatcher(zm.repeated(), TrueMatcher.INSTANCE); } else if (matcher instanceof CharSeqMatcher) { String pattern = matcher.<CharSeqMatcher>as().pattern(); return pattern.isEmpty() ? null : new CharSeqMatcher(pattern.charAt(0)); } else { return matcher; } } /** * Get the suffix matcher. This is similar to {@link #tail(Matcher)} except that it intended * to be used with {@link #getPrefix(Matcher)} */ static Matcher getSuffix(Matcher matcher) { if (matcher instanceof SeqMatcher) { List<Matcher> ms = matcher.<SeqMatcher>as().matchers(); return SeqMatcher.create(ms.subList(1, ms.size())); } else if (matcher instanceof ZeroOrMoreMatcher) { ZeroOrMoreMatcher zm = matcher.as(); return zm.next(); } else if (matcher instanceof CharSeqMatcher) { String pattern = matcher.<CharSeqMatcher>as().pattern(); return pattern.length() <= 1 ? TrueMatcher.INSTANCE : new CharSeqMatcher(pattern.substring(1)); } else { return TrueMatcher.INSTANCE; } } /** Compute the set of trigrams for an input string. */ public static SortedSet<String> computeTrigrams(String input) { if (input.length() < 3) { return Collections.emptySortedSet(); } else { SortedSet<String> trigrams = new TreeSet<>(); int n = input.length() - 3; for (int i = 0; i <= n; ++i) { trigrams.add(input.substring(i, i + 3)); } return trigrams; } } }
5,765
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/GreedyMatcher.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl.matcher; /** Base type for matchers that consume until next match. */ interface GreedyMatcher extends Matcher { /** Merge in the matcher that comes after in the sequence. */ Matcher mergeNext(Matcher after); }
5,766
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/ZeroOrOneMatcher.java
/* * Copyright 2014-2023 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl.matcher; import com.netflix.spectator.impl.Preconditions; import java.io.Serializable; import java.util.Objects; import java.util.SortedSet; import java.util.function.Function; /** * Matcher that looks for a pattern zero or one time followed by another pattern. */ final class ZeroOrOneMatcher implements GreedyMatcher, Serializable { private static final long serialVersionUID = 1L; private final Matcher repeated; private final Matcher next; /** Create a new instance. */ ZeroOrOneMatcher(Matcher repeated, Matcher next) { this.repeated = Preconditions.checkNotNull(repeated, "repeated"); this.next = Preconditions.checkNotNull(next, "next"); } /** Return the matcher for the repeated portion. */ Matcher repeated() { return repeated; } /** Return the matcher for the portion that follows. */ Matcher next() { return next; } @Override public String containedString() { return next.containedString(); } @Override public SortedSet<String> trigrams() { return next.trigrams(); } @Override public int matches(String str, int start, int length) { final int end = start + length; int pos = repeated.matches(str, start, end - start); if (pos >= start) { pos = next.matches(str, pos, end - pos); if (pos >= start) return pos; } return next.matches(str, start, end - start); } @Override public int minLength() { return next.minLength(); } @Override public boolean isEndAnchored() { return next.isEndAnchored(); } @Override public boolean alwaysMatches() { return repeated instanceof AnyMatcher && next instanceof TrueMatcher; } @Override public Matcher mergeNext(Matcher after) { if (after instanceof TrueMatcher) { return this; } Matcher m = (next instanceof TrueMatcher) ? after : SeqMatcher.create(next, after); return new ZeroOrOneMatcher(repeated, m); } @Override public Matcher rewrite(Function<Matcher, Matcher> f) { return f.apply(new ZeroOrOneMatcher(repeated.rewrite(f), next.rewrite(f))); } @Override public Matcher rewriteEnd(Function<Matcher, Matcher> f) { return f.apply(new ZeroOrOneMatcher(repeated, next.rewriteEnd(f))); } @Override public String toString() { return "(?:" + repeated + ")?" + (next instanceof TrueMatcher ? "" : next.toString()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ZeroOrOneMatcher that = (ZeroOrOneMatcher) o; return Objects.equals(repeated, that.repeated) && Objects.equals(next, that.next); } @Override public int hashCode() { int result = 1; result = 31 * result + repeated.hashCode(); result = 31 * result + next.hashCode(); return result; } }
5,767
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/PositiveLookaheadMatcher.java
/* * Copyright 2014-2022 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl.matcher; import java.io.Serializable; import java.util.Objects; import java.util.function.Function; /** * Matcher that does a positive lookahead. If the sub-matcher matches, then it will return * a match, but will not advance the position. */ final class PositiveLookaheadMatcher implements Matcher, Serializable { private static final long serialVersionUID = 1L; private final Matcher matcher; /** Create a new instance. */ PositiveLookaheadMatcher(Matcher matcher) { this.matcher = matcher; } Matcher matcher() { return matcher; } @Override public int matches(String str, int start, int length) { int pos = matcher.matches(str, start, length); return (pos >= 0) ? start : Constants.NO_MATCH; } @Override public int minLength() { return 0; } @Override public Matcher rewrite(Function<Matcher, Matcher> f) { return f.apply(new PositiveLookaheadMatcher(matcher.rewrite(f))); } @Override public Matcher rewriteEnd(Function<Matcher, Matcher> f) { return f.apply(new PositiveLookaheadMatcher(matcher.rewriteEnd(f))); } @Override public String toString() { return "(?=" + matcher + ")"; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PositiveLookaheadMatcher that = (PositiveLookaheadMatcher) o; return Objects.equals(matcher, that.matcher); } @Override public int hashCode() { int result = 1; result = 31 * result + matcher.hashCode(); return result; } }
5,768
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/Constants.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.impl.matcher; import com.netflix.spectator.impl.AsciiSet; import java.util.HashMap; import java.util.Map; /** Constants that are used by the various matchers. */ final class Constants { private Constants() { } /** Position returned to indicate that there is no match. */ static final int NO_MATCH = -1; /** Set of lower case alphabet characters. */ static final AsciiSet LOWER = AsciiSet.fromPattern("a-z"); /** Set of upper case alphabet characters. */ static final AsciiSet UPPER = AsciiSet.fromPattern("A-Z"); /** Set of all ASCII characters. */ static final AsciiSet ASCII = AsciiSet.all(); /** Set of lower and upper case alphabet characters. */ static final AsciiSet ALPHA = LOWER.union(UPPER); /** Set of decimal digit characters. */ static final AsciiSet DIGIT = AsciiSet.fromPattern("0-9"); /** Set containing the union of {@link #ALPHA} and {@link #DIGIT}. */ static final AsciiSet ALNUM = ALPHA.union(DIGIT); /** Set containing the common punctuation characters. */ static final AsciiSet PUNCT = AsciiSet.fromPattern("-!\"#$%&'()*+,./:;<=>?@[\\]^_`{|}~"); /** * Set containing the visible characters ({@link #ALPHA}, {@link #DIGIT}, and {@link #PUNCT}). */ static final AsciiSet GRAPH = PUNCT.union(ALNUM); /** Set containing the printable characters. */ static final AsciiSet PRINT = GRAPH.union(AsciiSet.fromPattern(" ")); /** Set containing space and tab. */ static final AsciiSet BLANK = AsciiSet.fromPattern(" \t"); /** Set containing the ASCII control characters. */ static final AsciiSet CNTRL = AsciiSet.control(); /** Set of hexadecimal digit characters. */ static final AsciiSet XDIGIT = AsciiSet.fromPattern("0-9a-fA-F"); /** Set containing the word characters. */ static final AsciiSet WORD_CHARS = AsciiSet.fromPattern("a-zA-Z_0-9"); /** Set containing the whitespace characters. */ static final AsciiSet SPACE = AsciiSet.fromPattern(" \t\n\u000B\f\r"); /** Character classes that can be looked up by name. */ static final Map<String, AsciiSet> NAMED_CHAR_CLASSES = new HashMap<>(); static { NAMED_CHAR_CLASSES.put("Lower", LOWER); NAMED_CHAR_CLASSES.put("Upper", UPPER); NAMED_CHAR_CLASSES.put("ASCII", ASCII); NAMED_CHAR_CLASSES.put("Alpha", ALPHA); NAMED_CHAR_CLASSES.put("Digit", DIGIT); NAMED_CHAR_CLASSES.put("Alnum", ALNUM); NAMED_CHAR_CLASSES.put("Punct", PUNCT); NAMED_CHAR_CLASSES.put("Graph", GRAPH); NAMED_CHAR_CLASSES.put("Print", PRINT); NAMED_CHAR_CLASSES.put("Blank", BLANK); NAMED_CHAR_CLASSES.put("Cntrl", CNTRL); NAMED_CHAR_CLASSES.put("XDigit", XDIGIT); NAMED_CHAR_CLASSES.put("Space", SPACE); } }
5,769
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/DefaultMaxGauge.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import com.netflix.spectator.impl.AtomicDouble; import java.util.Collections; /** Max gauge implementation for the default registry. */ class DefaultMaxGauge implements Gauge { private final Clock clock; private final Id id; private final AtomicDouble value; /** Create a new instance. */ DefaultMaxGauge(Clock clock, Id id) { this.clock = clock; this.id = id; this.value = new AtomicDouble(Double.NaN); } @Override public Id id() { return id; } @Override public Iterable<Measurement> measure() { final Measurement m = new Measurement(id, clock.wallTime(), value()); return Collections.singletonList(m); } @Override public boolean hasExpired() { return false; } @Override public void set(double v) { value.max(v); } @Override public double value() { return value.get(); } }
5,770
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/DefaultDistributionSummary.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicLong; /** Distribution summary implementation for the default registry. */ final class DefaultDistributionSummary implements DistributionSummary { private final Clock clock; private final Id id; private final AtomicLong count; private final AtomicLong totalAmount; /** Create a new instance. */ DefaultDistributionSummary(Clock clock, Id id) { this.clock = clock; this.id = id; count = new AtomicLong(0L); totalAmount = new AtomicLong(0L); } @Override public Id id() { return id; } @Override public boolean hasExpired() { return false; } @Override public void record(long amount) { if (amount >= 0) { totalAmount.addAndGet(amount); count.incrementAndGet(); } } @Override public Iterable<Measurement> measure() { final long now = clock.wallTime(); final List<Measurement> ms = new ArrayList<>(2); ms.add(new Measurement(id.withTag(Statistic.count), now, count.get())); ms.add(new Measurement(id.withTag(Statistic.totalAmount), now, totalAmount.get())); return ms; } @Override public long count() { return count.get(); } @Override public long totalAmount() { return totalAmount.get(); } }
5,771
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/NoopCounter.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import java.util.Collections; /** Counter implementation for the no-op registry. */ enum NoopCounter implements Counter { /** Singleton instance. */ INSTANCE; @Override public Id id() { return NoopId.INSTANCE; } @Override public boolean hasExpired() { return false; } @Override public void add(double amount) { } @Override public Iterable<Measurement> measure() { return Collections.emptyList(); } @Override public double actualCount() { return 0.0; } }
5,772
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/CompositeMeter.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Base class for composite implementations of core meter types. */ class CompositeMeter<T extends Meter> implements Meter { /** Identifier for the meter. */ protected final Id id; /** Underlying meters that are keeping the data. */ protected final Collection<T> meters; /** * Create a new instance. * * @param id * Identifier for the meter. * @param meters * Set of meters that make up the composite. */ CompositeMeter(Id id, Collection<T> meters) { this.id = id; this.meters = meters; } @Override public Id id() { return this.id; } @Override public boolean hasExpired() { for (Meter m : meters) { if (m != null && !m.hasExpired()) return false; } return true; } @Override public Iterable<Measurement> measure() { final List<Measurement> ms = new ArrayList<>(); for (Meter m : meters) { if (m != null) { for (Measurement measurement : m.measure()) { ms.add(measurement); } } } return ms; } }
5,773
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/BasicTag.java
/* * Copyright 2014-2021 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import com.netflix.spectator.impl.Preconditions; /** * Immutable implementation of Tag. */ public final class BasicTag implements Tag { /** * Convert an arbitrary implementation of {@link Tag} to BasicTag. When * used as part of an id this is needed to ensure correct behavior. Alternative * implementations will likely vary the hashCode/equals causing ids that should * be equivalent to not match as expected. */ static BasicTag convert(Tag t) { return (t instanceof BasicTag) ? (BasicTag) t : new BasicTag(t.key(), t.value()); } private final String key; private final String value; private int hc; /** * Construct a new instance. */ public BasicTag(String key, String value) { this.key = Preconditions.checkNotNull(key, "key"); this.value = value; if (value == null) { String msg = String.format("parameter 'value' cannot be null (key=%s)", key); throw new NullPointerException(msg); } } @Override public String key() { return key; } @Override public String value() { return value; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || !(obj instanceof BasicTag)) return false; BasicTag other = (BasicTag) obj; return key.equals(other.key) && value.equals(other.value); } @Override public int hashCode() { int h = hc; if (h == 0) { h = 31 * key.hashCode() + value.hashCode(); hc = h; } return h; } @Override public String toString() { return key + '=' + value; } }
5,774
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/Functions.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import com.netflix.spectator.impl.Preconditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Method; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Predicate; import java.util.function.ToDoubleFunction; /** * Common functions for use with gauges. */ public final class Functions { private static final Logger LOGGER = LoggerFactory.getLogger(Functions.class); private Functions() { } /** * Identity function that just returns the passed in value if it implements the * {@link java.lang.Number} interface. */ public static final DoubleFunction<? extends Number> IDENTITY = new DoubleFunction<Number>() { @Override public double apply(double v) { return v; } }; /** * Age function based on the system clock. See {@link #age(Clock)} for more details. */ public static final DoubleFunction<AtomicLong> AGE = age(Clock.SYSTEM); /** * Returns a function that computes the age in seconds. The value passed into the function * should be a timestamp in milliseconds since the epoch. Typically this will be the return * value from calling {@link java.lang.System#currentTimeMillis()}. * * @param clock * Clock used to get the current time for comparing with the passed in value. * @return * Function that computes the age. */ public static DoubleFunction<AtomicLong> age(final Clock clock) { return new DoubleFunction<AtomicLong>() { @Override public double apply(double t) { return (clock.wallTime() - t) / 1000.0; } }; } /** * Returns a function that invokes a method on the object via reflection. If an * exception of any kind occurs then NaN will be returned and the exception will be logged. * The method must have an empty parameter list and return a primitive number value or a * subclass of {@link java.lang.Number}. The method will be set accessible so that private * methods can be used. * * @param method * Method to execute on the passed in object. * @return * Value returned by the method or NaN if an exception is thrown. */ @SuppressWarnings("PMD.AvoidAccessibilityAlteration") public static <T> ToDoubleFunction<T> invokeMethod(final Method method) { method.setAccessible(true); return (obj) -> { try { final Number n = (Number) method.invoke(obj); return n.doubleValue(); } catch (Exception e) { LOGGER.warn("exception from method registered as a gauge [" + method + "]", e); return Double.NaN; } }; } /** * Returns a predicate that matches if the {code}id.name(){code} value for the input meter * is equal to {code}name{code}. Example of usage: * * <pre> * long numberOfMatches = registry.stream().filter(Functions.nameEquals("foo")).count(); * </pre> * * @param name * The name to use for finding matching meter instances. Cannot be null. * @return * A predicate function that can be used to filter a stream. */ public static Predicate<Meter> nameEquals(String name) { Preconditions.checkNotNull(name, "name"); return m -> name.equals(m.id().name()); } }
5,775
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/Id.java
/* * Copyright 2014-2020 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.BiPredicate; import java.util.function.Predicate; /** * Identifier for a meter or measurement. */ public interface Id extends TagList { /** Description of the measurement that is being collected. */ String name(); /** Other dimensions that can be used to classify the measurement. */ Iterable<Tag> tags(); /** Return a new id with an additional tag value. */ Id withTag(String k, String v); /** Return a new id with an additional tag value. */ Id withTag(Tag t); /** * Return a new id with an additional tag value using {@link Boolean#toString(boolean)} to * convert the boolean value to a string representation. This is merely a convenience function * for: * * <pre> * id.withTag("key", Boolean.toString(value)) * </pre> */ default Id withTag(String k, boolean v) { return withTag(k, Boolean.toString(v)); } /** * Return a new id with an additional tag value using {@link Enum#name()} to * convert the Enum to a string representation. This is merely a convenience function * for: * * <pre> * id.withTag("key", myEnum.name()) * </pre> */ default <E extends Enum<E>> Id withTag(String k, Enum<E> v) { return withTag(k, v.name()); } /** * Return a new id with additional tag values. This overload is to avoid allocating a * parameters array for the more generic varargs method {@link #withTags(String...)}. */ default Id withTags(String k1, String v1) { return withTag(k1, v1); } /** * Return a new id with additional tag values. This overload is to avoid allocating a * parameters array for the more generic varargs method {@link #withTags(String...)}. */ @SuppressWarnings("PMD.UseObjectForClearerAPI") default Id withTags(String k1, String v1, String k2, String v2) { // The original reason for this method was to avoid allocating a string array before // creating a Tag array. The internals have changed so it can work on the string array // directly. The overload is kept for backwards compatiblity. final String[] ts = { k1, v1, k2, v2 }; return withTags(ts); } /** * Return a new id with additional tag values. This overload is to avoid allocating a * parameters array for the more generic varargs method {@link #withTags(String...)}. */ @SuppressWarnings("PMD.UseObjectForClearerAPI") default Id withTags(String k1, String v1, String k2, String v2, String k3, String v3) { // The original reason for this method was to avoid allocating a string array before // creating a Tag array. The internals have changed so it can work on the string array // directly. The overload is kept for backwards compatiblity. final String[] ts = { k1, v1, k2, v2, k3, v3 }; return withTags(ts); } /** Return a new id with additional tag values. */ default Id withTags(String... tags) { Id tmp = this; for (int i = 0; i < tags.length; i += 2) { tmp = tmp.withTag(tags[i], tags[i + 1]); } return tmp; } /** Return a new id with additional tag values. */ default Id withTags(Tag... tags) { Id tmp = this; for (Tag t : tags) { tmp = tmp.withTag(t); } return tmp; } /** Return a new id with additional tag values. */ default Id withTags(Iterable<Tag> tags) { Id tmp = this; for (Tag t : tags) { tmp = tmp.withTag(t); } return tmp; } /** * Return a new id with additional tag values. * * If using a {@link java.util.concurrent.ConcurrentMap}, note that the map <strong>should * not</strong> be concurrently modified during this call. It is up to the user to ensure * that it contains the correct set of tags that should be added to the id before and for the * entire duration of the call until the new id is returned. */ default Id withTags(Map<String, String> tags) { Id tmp = this; for (Map.Entry<String, String> entry : tags.entrySet()) { tmp = tmp.withTag(entry.getKey(), entry.getValue()); } return tmp; } /** Return the key at the specified index. The name will be treated as position 0. */ @Override default String getKey(int i) { return i == 0 ? "name" : Utils.getValue(tags(), i - 1).key(); } /** Return the value at the specified index. The name will be treated as position 0. */ @Override default String getValue(int i) { return i == 0 ? name() : Utils.getValue(tags(), i - 1).value(); } /** Return the size, number of tags, for the id including the name. */ @Override default int size() { return Utils.size(tags()) + 1; } /** Return a new tag list with only tags that match the predicate. */ @Override default Id filter(BiPredicate<String, String> predicate) { List<Tag> filtered = new ArrayList<>(); for (Tag tag : tags()) { if (predicate.test(tag.key(), tag.value())) { filtered.add(tag); } } return new DefaultId(name(), ArrayTagSet.create(filtered)); } /** Return a new tag list with only tags with keys that match the predicate. */ @Override default Id filterByKey(Predicate<String> predicate) { return filter((k, v) -> predicate.test(k)); } /** * Create an immutable Id with the provided name. In many cases it is preferable to use * {@link Registry#createId(String)} instead so that the overhead for instrumentation can * be mostly removed when choosing to use a NoopRegistry. Using this method directly the Id * will always be created. */ static Id create(String name) { return new DefaultId(name); } /** * <b>Warning:</b> This method can be used to get better performance for some critical * use-cases, but also has increased risk. If there is any doubt, then use * {@link #create(String)} instead. * * <p>Create a new id using the name tag set. The provided array will be used directly so * it should not be modified after. Caller must ensure that:</p> * * <ul> * <li>Length of tags array is even.</li> * <li>There are no null values for the first length entries in the array.</li> * </ul> */ static Id unsafeCreate(String name, String[] tags, int length) { return new DefaultId(name, ArrayTagSet.unsafeCreate(tags, length)); } }
5,776
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/SwapCounter.java
/* * Copyright 2014-2022 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import com.netflix.spectator.impl.SwapMeter; import java.util.function.Consumer; import java.util.function.LongSupplier; import java.util.function.Supplier; /** Wraps another counter allowing the underlying type to be swapped. */ final class SwapCounter extends SwapMeter<Counter> implements Counter { /** Create a new instance. */ SwapCounter(Registry registry, LongSupplier versionSupplier, Id id, Counter underlying) { super(registry, versionSupplier, id, underlying); } @Override public Counter lookup() { return registry.counter(id); } @Override public void add(double amount) { get().add(amount); } @Override public double actualCount() { return get().actualCount(); } @SuppressWarnings("unchecked") @Override public BatchUpdater batchUpdater(int batchSize) { BatchUpdater updater = get().batchUpdater(batchSize); // Registry implementations can implement `Consumer<Supplier<Counter>>` to allow the // meter to be resolved when flushed and avoid needing to hold on to a particular // instance of the meter that might have expired and been removed from the registry. if (updater instanceof Consumer<?>) { ((Consumer<Supplier<Counter>>) updater).accept(this::get); } return updater; } }
5,777
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/CompositeTimer.java
/* * Copyright 2014-2023 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.TimeUnit; /** Timer implementation for the composite registry. */ final class CompositeTimer extends CompositeMeter<Timer> implements Timer { private final Clock clock; /** Create a new instance. */ CompositeTimer(Id id, Clock clock, Collection<Timer> timers) { super(id, timers); this.clock = clock; } @Override public Clock clock() { return clock; } @Override public void record(long amount, TimeUnit unit) { for (Timer t : meters) { t.record(amount, unit); } } @Override public long count() { Iterator<Timer> it = meters.iterator(); return it.hasNext() ? it.next().count() : 0L; } @Override public long totalTime() { Iterator<Timer> it = meters.iterator(); return it.hasNext() ? it.next().totalTime() : 0L; } }
5,778
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/NoopGauge.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import java.util.Collections; /** Gauge implementation for the no-op registry. */ enum NoopGauge implements Gauge { /** Singleton instance. */ INSTANCE; @Override public Id id() { return NoopId.INSTANCE; } @Override public Iterable<Measurement> measure() { return Collections.emptyList(); } @Override public boolean hasExpired() { return false; } @Override public void set(double v) { } @Override public double value() { return Double.NaN; } }
5,779
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/CompositeDistributionSummary.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import java.util.Collection; import java.util.Iterator; /** Distribution summary implementation for the composite registry. */ final class CompositeDistributionSummary extends CompositeMeter<DistributionSummary> implements DistributionSummary { /** Create a new instance. */ CompositeDistributionSummary(Id id, Collection<DistributionSummary> summaries) { super(id, summaries); } @Override public void record(long amount) { for (DistributionSummary d : meters) { d.record(amount); } } @Override public long count() { Iterator<DistributionSummary> it = meters.iterator(); return it.hasNext() ? it.next().count() : 0L; } @Override public long totalAmount() { Iterator<DistributionSummary> it = meters.iterator(); return it.hasNext() ? it.next().totalAmount() : 0L; } }
5,780
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/Gauge.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; /** * A meter with a single value that can only be sampled at a point in time. A typical example is * a queue size. */ public interface Gauge extends Meter { /** * Set the current value of the gauge. * * @param value * Most recent measured value. */ default void set(double value) { // For backwards compatibility with older versions of spectator prior to set being // required on the gauge. Default implementation should be removed in a future release. } /** Returns the current value. */ double value(); }
5,781
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/RegistryConfig.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import java.time.Duration; /** * Configuration settings for the registry. */ public interface RegistryConfig { /** * Get the value associated with a key. * * @param k * Key to lookup in the config. * @return * Value for the key or null if no key is present. */ String get(String k); /** Should an exception be thrown for warnings? */ default boolean propagateWarnings() { String v = get("propagateWarnings"); return v != null && Boolean.parseBoolean(v); } /** * For classes based on {@link com.netflix.spectator.api.AbstractRegistry} this setting is used * to determine the maximum number of registered meters permitted. This limit is used to help * protect the system from a memory leak if there is a bug or irresponsible usage of registering * meters. * * @return * Maximum number of distinct meters that can be registered at a given time. The default is * {@link java.lang.Integer#MAX_VALUE}. */ default int maxNumberOfMeters() { String v = get("maxNumberOfMeters"); return (v == null) ? Integer.MAX_VALUE : Integer.parseInt(v); } /** How often registered gauges should get polled. */ default Duration gaugePollingFrequency() { String v = get("gaugePollingFrequency"); return (v == null) ? Duration.ofSeconds(10) : Duration.parse(v); } }
5,782
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/DefaultGauge.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import com.netflix.spectator.impl.AtomicDouble; import java.util.Collections; /** Counter implementation for the default registry. */ class DefaultGauge implements Gauge { private final Clock clock; private final Id id; private final AtomicDouble value; /** Create a new instance. */ DefaultGauge(Clock clock, Id id) { this.clock = clock; this.id = id; this.value = new AtomicDouble(Double.NaN); } @Override public Id id() { return id; } @Override public Iterable<Measurement> measure() { final Measurement m = new Measurement(id, clock.wallTime(), value()); return Collections.singletonList(m); } @Override public boolean hasExpired() { return false; } @Override public void set(double v) { value.set(v); } @Override public double value() { return value.get(); } }
5,783
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/Tag.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; /** Key/value pair used to classify and drill into measurements. */ public interface Tag { /** Key for the tag. */ String key(); /** Value for the tag. */ String value(); /** Create an immutable instance of a tag. */ static Tag of(String key, String value) { return new BasicTag(key, value); } }
5,784
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/AbstractMeter.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import java.lang.ref.WeakReference; /** * Helper base class for meters that maintains a weak reference to the object being measured. * Meters that are based on polling rather than activity need some other way to define the * lifespan and in this case that is if the reference still exists. Basing this off a weak * reference means there doesn't need to be an explicit de-registration and registering to * collect insight will not prevent garbage collection of the underlying object. */ public abstract class AbstractMeter<T> implements Meter { /** Clock to use for getting measurement timestamps. */ protected final Clock clock; /** Identifier for the meter. */ protected final Id id; /** Reference to the underlying object used to compute the measurements. */ protected final WeakReference<T> ref; /** * Create a new instance. * * @param clock * Clock to use for getting measurement timestamps. Typically should be the clock used by * the registry (see {@link Registry#clock()}). * @param id * Identifier for the meter. * @param obj * Reference to the underlying object used to compute the measurements. */ public AbstractMeter(Clock clock, Id id, T obj) { this.clock = clock; this.id = id; this.ref = new WeakReference<>(obj); } @Override public Id id() { return this.id; } @Override public boolean hasExpired() { return this.ref.get() == null; } }
5,785
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/Spectator.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; /** * Static factory used to access the main global registry. */ public final class Spectator { private static final CompositeRegistry COMPOSITE_REGISTRY = new CompositeRegistry(Clock.SYSTEM); private static final ExtendedRegistry REGISTRY = new ExtendedRegistry(COMPOSITE_REGISTRY); /** * Returns the global registry. * * @deprecated Use injection or {@link #globalRegistry()} instead. This method is scheduled * for removal in a future release. */ @Deprecated public static ExtendedRegistry registry() { return REGISTRY; } /** * Returns the global composite registry. This method can be used for use-cases where it is * necessary to get a static reference to a registry. It will not do anything unless other * registries are added. Example: * * <pre> * class Main { * public static void main(String[] args) { * // This is the preferred usage and works well with DI libraries like guice. Setup a * // registry and pass it in as needed. * Registry registry = new DefaultRegistry(); * (new Example1(registry)).start(); * * // If it is desirable to get data from things using the global registry, then the * // registry for the application can be added to the global context. * Spectator.globalRegistry().add(registry); * Example2 ex2 = new Example2(); * ex2.start(); * * // If the lifecycle is not the same as the jvm, then the registry should be removed * // when shutting down. * ex2.onShutdown(() -> Spectator.globalRegistry().remove(registry)); * } * } * * class Example1 { * private final Counter c; * * Example1(Registry registry) { * c = registry.counter("example1"); * } * ... * } * * class Example2 { * private final Counter c; * * Example2() { * c = Spectator.globalRegistry().counter("example1"); * } * ... * } * </pre> */ public static CompositeRegistry globalRegistry() { return COMPOSITE_REGISTRY; } private Spectator() { } }
5,786
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/NoopId.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.Spliterator; import java.util.Spliterators; import java.util.function.BiPredicate; import java.util.function.Predicate; /** Id implementation for the no-op registry. */ final class NoopId implements Id { /** Singleton instance. */ static final Id INSTANCE = new NoopId(); private NoopId() { } @Override public String name() { return "noop"; } @Override public Iterable<Tag> tags() { return Collections.emptyList(); } @Override public Id withTag(String k, String v) { return this; } @Override public Id withTag(Tag tag) { return this; } @Override public Id withTags(Iterable<Tag> tags) { return this; } @Override public Id withTags(Tag... tags) { return this; } @Override public Id withTags(String... tags) { return this; } @Override public Id withTags(Map<String, String> tags) { return this; } @Override public Id withTag(String k, boolean v) { return this; } @SuppressWarnings("PMD.UseObjectForClearerAPI") @Override public Id withTags(String k1, String v1, String k2, String v2) { return this; } @SuppressWarnings("PMD.UseObjectForClearerAPI") @Override public Id withTags(String k1, String v1, String k2, String v2, String k3, String v3) { return this; } @Override public String toString() { return name(); } @Override public String getKey(int i) { return "name"; } @Override public String getValue(int i) { return name(); } @Override public int size() { return 1; } @Override public Id filter(BiPredicate<String, String> predicate) { return this; } @Override public Id filterByKey(Predicate<String> predicate) { return this; } @Override public Iterator<Tag> iterator() { return Collections.emptyIterator(); } @Override public Spliterator<Tag> spliterator() { return Spliterators.emptySpliterator(); } }
5,787
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/ArrayTagSet.java
/* * Copyright 2014-2023 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import com.netflix.spectator.impl.Preconditions; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.SortedMap; import java.util.Spliterator; import java.util.Spliterators; import java.util.concurrent.ConcurrentMap; import java.util.function.BiPredicate; import java.util.function.Predicate; /** * An immutable set of tags sorted by the tag key. */ final class ArrayTagSet implements TagList { /** Empty tag set. */ static final ArrayTagSet EMPTY = new ArrayTagSet(new String[0]); /** Create a new tag set. */ static ArrayTagSet create(String... tags) { return EMPTY.addAll(tags); } /** Create a new tag set. */ static ArrayTagSet create(Tag... tags) { return EMPTY.addAll(tags); } /** Create a new tag set. */ static ArrayTagSet create(Iterable<Tag> tags) { return (tags instanceof ArrayTagSet) ? (ArrayTagSet) tags : EMPTY.addAll(tags); } /** Create a new tag set. */ static ArrayTagSet create(Map<String, String> tags) { return EMPTY.addAll(tags); } /** * This method can be used to get better performance for some critical use-cases, but also * has increased risk. If there is any doubt, then use {@link #create(Tag...)} instead. * * <p>Create a new tag set based on the provided array. The provided array will be used * so it should not be modified after. Caller must ensure that:</p> * * <ul> * <li>Length of tags array is even.</li> * <li>There are no null values for the first length entries in the array.</li> * </ul> */ static ArrayTagSet unsafeCreate(String[] tags, int length) { insertionSort(tags, length); int len = dedupInPlace(tags, length); return new ArrayTagSet(tags, len); } private final String[] tags; private final int length; private int cachedHashCode; private ArrayTagSet(String[] tags) { this(tags, tags.length); } private ArrayTagSet(String[] tags, int length) { if (tags.length % 2 != 0) { throw new IllegalArgumentException("length of tags array must be even"); } if (length > tags.length) { throw new IllegalArgumentException("length cannot be larger than tags array"); } this.tags = tags; this.length = length; this.cachedHashCode = 0; } /** Check if this set is empty. */ boolean isEmpty() { return length == 0; } /** Add a new tag to the set. */ ArrayTagSet add(String k, String v) { Preconditions.checkNotNull(k, "key"); Preconditions.checkNotNull(v, "value"); if (length == 0) { return new ArrayTagSet(new String[] {k, v}); } int idx = 0; int cmp = -1; while (idx < length) { cmp = tags[idx].compareTo(k); if (cmp >= 0) { break; } idx += 2; } // Update an existing tag if (cmp == 0) { if (tags[idx + 1].equals(v)) { return this; } String[] newTags = Arrays.copyOf(tags, length); newTags[idx + 1] = v; return new ArrayTagSet(newTags); } String[] newTags = new String[length + 2]; newTags[idx] = k; newTags[idx + 1] = v; System.arraycopy(tags, 0, newTags, 0, idx); System.arraycopy(tags, idx, newTags, idx + 2, length - idx); return new ArrayTagSet(newTags); } /** Add a new tag to the set. */ ArrayTagSet add(Tag tag) { return add(tag.key(), tag.value()); } /** Add a collection of tags to the set. */ ArrayTagSet addAll(Iterable<Tag> ts) { if (ts instanceof Collection) { Collection<Tag> data = (Collection<Tag>) ts; if (data.isEmpty()) { return this; } else { String[] newTags = new String[2 * data.size()]; int i = 0; for (Tag t : data) { newTags[i++] = t.key(); newTags[i++] = t.value(); } checkForNullValues(newTags); return addAll(newTags, newTags.length); } } else if (ts instanceof TagList) { if (ts instanceof ArrayTagSet) { return addAll((ArrayTagSet) ts); } return addAll((TagList) ts); } else { List<Tag> data = new ArrayList<>(); for (Tag t : ts) { data.add(t); } return addAll(data); } } /** Add a collection of tags to the set. */ ArrayTagSet addAll(Map<String, String> ts) { if (ts.isEmpty()) { return this; } else if (ts instanceof ConcurrentMap) { // Special case ConcurrentMaps to avoid propagating errors if there is a bug in the caller // and the map is mutated while being added: // https://github.com/Netflix/spectator/issues/733 List<Tag> data = new ArrayList<>(ts.size()); for (Map.Entry<String, String> entry : ts.entrySet()) { data.add(new BasicTag(entry.getKey(), entry.getValue())); } return addAll(data); } else { String[] newTags = new String[2 * ts.size()]; int i = 0; for (Map.Entry<String, String> entry : ts.entrySet()) { newTags[i++] = Objects.requireNonNull(entry.getKey(), "tag keys cannot be null"); newTags[i++] = Objects.requireNonNull(entry.getValue(), "tag values cannot be null"); } boolean sorted = ts instanceof SortedMap && isNaturallyOrdered((SortedMap<String, String>) ts); return addAll(newTags, newTags.length, sorted, true); } } /** Add a collection of tags to the set. */ ArrayTagSet addAll(String[] ts) { if (ts.length % 2 != 0) { throw new IllegalArgumentException("array length must be even, (length=" + ts.length + ")"); } checkForNullValues(ts); String[] copy = Arrays.copyOf(ts, ts.length); return addAll(copy, copy.length); } private ArrayTagSet addAll(String[] ts, int tsLength) { return addAll(ts, tsLength, false, false); } /** Add a collection of tags to the set. */ private ArrayTagSet addAll(String[] ts, int tsLength, boolean sorted, boolean distinct) { if (tsLength == 0) { return this; } else if (length == 0) { if (!sorted) { insertionSort(ts, tsLength); } int len = tsLength; if (!distinct) { len = dedup(ts, 0, ts, 0, tsLength); } return new ArrayTagSet(ts, len); } else { String[] newTags = new String[length + tsLength]; if (!sorted) { insertionSort(ts, tsLength); } int newLength = merge(newTags, tags, length, ts, tsLength); return new ArrayTagSet(newTags, newLength); } } private ArrayTagSet addAll(ArrayTagSet ts) { if (ts == this || ts.isEmpty()) { return this; } if (isEmpty()) { return ts; } String[] newTags = new String[length + ts.length]; int newLength = merge(newTags, tags, length, ts.tags, ts.length); return new ArrayTagSet(newTags, newLength); } private ArrayTagSet addAll(TagList ts) { int size = ts.size(); if (size == 0) { return this; } String[] newTags = new String[size * 2]; int j = 0; for (int i = 0; i < size; i++) { newTags[j++] = Objects.requireNonNull(ts.getKey(i), "tag keys cannot be null"); newTags[j++] = Objects.requireNonNull(ts.getValue(i), "tag values cannot be null"); } return addAll(newTags, newTags.length); } /** Add a collection of tags to the set. */ ArrayTagSet addAll(Tag[] ts) { return addAll(ts, ts.length); } /** Add a collection of tags to the set. */ ArrayTagSet addAll(Tag[] ts, int tsLength) { if (tsLength == 0) { return this; } else { String[] newTags = toStringArray(ts, tsLength); checkForNullValues(newTags); return addAll(newTags, newTags.length); } } private String[] toStringArray(Tag[] ts, int length) { String[] strs = new String[length * 2]; for (int i = 0; i < length; ++i) { strs[2 * i] = ts[i].key(); strs[2 * i + 1] = ts[i].value(); } return strs; } private void checkForNullValues(String[] ts) { for (String s : ts) { if (s == null) { throw new NullPointerException("tag keys and values cannot be null"); } } } /** * Sort a string array that consists of tag key/value pairs by key. The array will be * sorted in-place. Tag lists are supposed to be fairly small, typically less than 20 * tags. With the small size a simple insertion sort works well. */ private static void insertionSort(String[] ts, int length) { if (length == 4) { // Two key/value pairs, swap if needed if (ts[0].compareTo(ts[2]) > 0) { // Swap key String tmp = ts[0]; ts[0] = ts[2]; ts[2] = tmp; // Swap value tmp = ts[1]; ts[1] = ts[3]; ts[3] = tmp; } } else if (length > 4) { // One entry is already sorted. Two entries handled above, for larger arrays // use insertion sort. for (int i = 2; i < length; i += 2) { String k = ts[i]; String v = ts[i + 1]; int j = i - 2; for (; j >= 0 && ts[j].compareTo(k) > 0; j -= 2) { ts[j + 2] = ts[j]; ts[j + 3] = ts[j + 1]; } ts[j + 2] = k; ts[j + 3] = v; } } } /** * Merge and dedup any entries in {@code ts} that have the same key. The last entry * with a given key will get selected. Each list must be sorted by key before processing. */ static int merge(String[] dst, String[] srcA, int lengthA, String[] srcB, int lengthB) { int i = 0; int ai = 0; int bi = 0; while (ai < lengthA && bi < lengthB) { final String ak = srcA[ai]; final String av = srcA[ai + 1]; String bk = srcB[bi]; String bv = srcB[bi + 1]; int cmp = ak.compareTo(bk); if (cmp < 0) { // srcA should already have been deduped as it comes from the tag list dst[i++] = ak; dst[i++] = av; ai += 2; } else if (cmp > 0) { // Choose last value for a given key if there are duplicates. It is possible srcB // will contain duplicates if the user supplied a type like a list. int j = bi + 2; for (; j < lengthB && bk.equals(srcB[j]); j += 2) { bv = srcB[j + 1]; } dst[i++] = bk; dst[i++] = bv; bi = j; } else { // Newer tags should override, use source B if there are duplicate keys. // If source B has duplicates, then use the last value for the given key. int j = bi + 2; for (; j < lengthB && ak.equals(srcB[j]); j += 2) { bk = srcB[j]; bv = srcB[j + 1]; } dst[i++] = bk; dst[i++] = bv; bi = j; ai += 2; // Ignore } } if (ai < lengthA) { System.arraycopy(srcA, ai, dst, i, lengthA - ai); i += lengthA - ai; } else if (bi < lengthB) { i = dedup(srcB, bi, dst, i, lengthB - bi); } return i; } /** * Dedup any entries in {@code ts} that have the same key. The last entry with a given * key will get selected. Input data must already be sorted by the tag key. Returns the * length of the overall deduped array. */ private static int dedup(String[] src, int ss, String[] dst, int ds, int len) { if (len == 0) { return ds; } else { String k = src[ss]; dst[ds] = k; dst[ds + 1] = src[ss + 1]; int j = ds; final int e = ss + len; for (int i = ss + 2; i < e; i += 2) { if (k.equals(src[i])) { dst[j] = src[i]; dst[j + 1] = src[i + 1]; } else { j += 2; // Not deduping, skip over previous entry k = src[i]; dst[j] = k; dst[j + 1] = src[i + 1]; } } return j + 2; } } /** * Dedup any entries in {@code data} that have the same key. The last entry with a given * key will get selected. Input data must already be sorted by the tag key. Returns the * length of the overall deduped array. */ private static int dedupInPlace(String[] data, int len) { if (len == 0) { return 0; } else { String k = data[0]; int j = 0; for (int i = 2; i < len; i += 2) { if (k.equals(data[i])) { data[j] = data[i]; data[j + 1] = data[i + 1]; } else { j += 2; // Not deduping, skip over previous entry k = data[i]; if (i > j) { data[j] = k; data[j + 1] = data[i + 1]; } } } return j + 2; } } /** Return the key at the specified position. */ @Override public String getKey(int i) { return tags[i * 2]; } /** Return the value at the specified position. */ @Override public String getValue(int i) { return tags[i * 2 + 1]; } /** Return the current size of this tag set. */ @Override public int size() { return length / 2; } @Override public ArrayTagSet filter(BiPredicate<String, String> predicate) { final int n = size(); String[] result = new String[2 * n]; int pos = 0; for (int i = 0; i < n; ++i) { final String k = getKey(i); final String v = getValue(i); if (predicate.test(k, v)) { result[pos++] = k; result[pos++] = v; } } return new ArrayTagSet(result, pos); } @Override public ArrayTagSet filterByKey(Predicate<String> predicate) { return filter((k, v) -> predicate.test(k)); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ArrayTagSet other = (ArrayTagSet) o; if (length != other.length) return false; for (int i = 0; i < length; ++i) { if (!tags[i].equals(other.tags[i])) return false; } return true; } @Override public int hashCode() { int hc = cachedHashCode; if (hc == 0) { hc = 1; for (int i = 0; i < length; ++i) { hc = 31 * hc + tags[i].hashCode(); } cachedHashCode = hc; } return hc; } @Override public String toString() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < length; i += 2) { builder.append(':').append(tags[i]).append('=').append(tags[i + 1]); } return builder.toString(); } @Override public Spliterator<Tag> spliterator() { return Spliterators.spliterator(iterator(), size(), (Spliterator.ORDERED | Spliterator.SORTED | Spliterator.NONNULL | Spliterator.DISTINCT | Spliterator.IMMUTABLE)); } private static boolean isNaturallyOrdered(SortedMap<?, ?> map) { return map.comparator() == null || Comparator.naturalOrder().equals(map.comparator()); } }
5,788
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/Statistic.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; /** * The valid set of statistics that can be reported by timers and distribution summaries. */ public enum Statistic implements Tag { /** A value sampled at a point in time. */ gauge, /** Rate per second for calls to record. */ count, /** The maximum amount recorded. */ max, /** The sum of the amounts recorded. */ totalAmount, /** The sum of the squares of the amounts recorded. */ totalOfSquares, /** The sum of the times recorded. */ totalTime, /** Number of currently active tasks for a long task timer. */ activeTasks, /** Duration of a running task. */ duration, /** Value used to compute a distributed percentile estimate. */ percentile; @Override public String key() { return "statistic"; } @Override public String value() { return name(); } }
5,789
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/Utils.java
/* * Copyright 2014-2021 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import com.netflix.spectator.impl.Preconditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.concurrent.ConcurrentMap; import java.util.function.Function; import java.util.function.Predicate; /** * Helper functions for working with a sequence of measurements. */ public final class Utils { private static final Logger REGISTRY_LOGGER = LoggerFactory.getLogger(Registry.class); private Utils() { } /** Search for a method in the class and all superclasses. */ static Method getMethod(Class<?> cls, String name) throws NoSuchMethodException { NoSuchMethodException firstExc = null; for (Class<?> c = cls; c != null; c = c.getSuperclass()) { try { return c.getDeclaredMethod(name); } catch (NoSuchMethodException e) { if (firstExc == null) { firstExc = e; } } } throw firstExc; } /** Return a method supplying a value for a gauge. */ static Method getGaugeMethod(Registry registry, Id id, Object obj, String method) { try { final Method m = Utils.getMethod(obj.getClass(), method); try { // Make sure we can cast the response to a Number final Number n = (Number) m.invoke(obj); REGISTRY_LOGGER.debug( "registering gauge {}, using method [{}], with initial value {}", id, m, n); return m; } catch (Exception e) { final String msg = "exception thrown invoking method [" + m + "], skipping registration of gauge " + id; registry.propagate(msg, e); } } catch (NoSuchMethodException e) { final String mname = obj.getClass().getName() + "." + method; final String msg = "invalid method [" + mname + "], skipping registration of gauge " + id; registry.propagate(msg, e); } catch (Exception e) { registry.propagate(e); } return null; } /** * Returns a new id with the tag list sorted by key and with no duplicate keys. */ public static Id normalize(Id id) { return (new DefaultId(id.name())).withTags(id.tags()).normalize(); } /** * Returns the value associated with with a given key or null if no such key is present in the * set of tags. * * @param id * Identifier with a set of tags to search. * @param k * Key to search for. * @return * Value for the key or null if the key is not present. */ public static String getTagValue(Id id, String k) { Preconditions.checkNotNull(id, "id"); return getTagValue(id.tags(), k); } /** * Returns the value associated with with a given key or null if no such key is present in the * set of tags. * * @param tags * Set of tags to search. * @param k * Key to search for. * @return * Value for the key or null if the key is not present. */ public static String getTagValue(Iterable<Tag> tags, String k) { Preconditions.checkNotNull(tags, "tags"); Preconditions.checkNotNull(k, "key"); if (tags instanceof TagList) { TagList list = (TagList) tags; int n = list.size(); for (int i = 0; i < n; ++i) { if (k.equals(list.getKey(i))) { return list.getValue(i); } } } else { for (Tag t : tags) { if (k.equals(t.key())) { return t.value(); } } } return null; } /** * Return the value at a given position in the iterable. * * @param values * A collection of values. For deterministic behavior the iteration order of the * container type must be consistent each time. * @param pos * Position of the value to extract. * @return * Value at the given position. */ public static <T> T getValue(Iterable<T> values, int pos) { if (values instanceof List) { List<T> vs = (List<T>) values; return vs.get(pos); } else { int i = 0; for (T v : values) { if (i == pos) { return v; } ++i; } throw new IndexOutOfBoundsException(pos + " >= " + i); } } /** * Returns the first measurement with a given tag value. * * @param ms * A set of measurements. * @param t * The key and value to search for. * @return * Measurement or null if no matches are found. */ public static Measurement first(Iterable<Measurement> ms, Tag t) { return first(ms, t.key(), t.value()); } /** * Returns the first measurement with a given tag value. * * @param ms * A set of measurements. * @param k * Key to search for. * @param v * Value that should be associated with k on the ids. * @return * Measurement or null if no matches are found. */ public static Measurement first(final Iterable<Measurement> ms, final String k, final String v) { return first(ms, value -> v.equals(getTagValue(value.id(), k))); } /** * Returns the first measurement that matches the predicate. * * @param ms * A set of measurements. * @param p * Predicate to use for selecting values. * @return * Measurement or null if no matches are found. */ public static Measurement first(Iterable<Measurement> ms, Predicate<Measurement> p) { Iterator<Measurement> it = filter(ms, p).iterator(); return it.hasNext() ? it.next() : null; } /** * Returns a new iterable restricted to measurements that match the predicate. * * @param ms * A set of measurements. * @param t * The key and value to search for. * @return * Measurements matching the predicate. */ public static Iterable<Measurement> filter(Iterable<Measurement> ms, Tag t) { return filter(ms, t.key(), t.value()); } /** * Returns a new iterable restricted to measurements that match the predicate. * * @param ms * A set of measurements. * @param k * Key to search for. * @param v * Value that should be associated with k on the ids. * @return * Measurements matching the predicate. */ public static Iterable<Measurement> filter( final Iterable<Measurement> ms, final String k, final String v) { return filter(ms, value -> v.equals(getTagValue(value.id(), k))); } /** * Returns a new iterable restricted to measurements that match the predicate. * * @param ms * A set of measurements. * @param p * Predicate to use for selecting values. * @return * Measurements matching the predicate. */ public static Iterable<Measurement> filter( final Iterable<Measurement> ms, final Predicate<Measurement> p) { return () -> new FilteredIterator<>(ms.iterator(), p); } /** * Returns a list with a copy of the data from the iterable. */ public static <T> List<T> toList(Iterable<T> iter) { List<T> buf = new ArrayList<>(); for (T v : iter) { buf.add(v); } return buf; } /** * Returns a list with the data from the iterator. */ public static <T> List<T> toList(Iterator<T> iter) { List<T> buf = new ArrayList<>(); while (iter.hasNext()) { buf.add(iter.next()); } return buf; } /** * Returns the size of an iterable. This method should only be used with fixed size * collections. It will attempt to find an efficient method to get the size before falling * back to a traversal of the iterable. */ @SuppressWarnings("PMD.UnusedLocalVariable") public static <T> int size(Iterable<T> iter) { if (iter instanceof TagList) { return ((TagList) iter).size(); } else if (iter instanceof Collection<?>) { return ((Collection<?>) iter).size(); } else { int size = 0; for (T v : iter) { ++size; } return size; } } /** * Returns an iterable of tags based on a string array. */ static Iterable<Tag> toIterable(String[] tags) { if (tags.length % 2 == 1) { throw new IllegalArgumentException("size must be even, it is a set of key=value pairs"); } ArrayList<Tag> ts = new ArrayList<>(tags.length / 2); for (int i = 0; i < tags.length; i += 2) { ts.add(new BasicTag(tags[i], tags[i + 1])); } return ts; } /** * This method should be used instead of the * {@link ConcurrentMap#computeIfAbsent(Object, Function)} call to minimize * thread contention. This method does not require locking for the common case * where the key exists, but potentially performs additional computation when * absent. */ public static <K, V> V computeIfAbsent(ConcurrentMap<K, V> map, K k, Function<K, V> f) { V v = map.get(k); if (v == null) { V tmp = f.apply(k); v = map.putIfAbsent(k, tmp); if (v == null) { v = tmp; } } return v; } /** * Propagate a type error exception. Used in situations where an existing id has already * been registered but with a different class. */ public static void propagateTypeError( Registry registry, Id id, Class<?> desiredClass, Class<?> actualClass) { final String dType = desiredClass.getName(); final String aType = actualClass.getName(); final String msg = String.format("cannot access '%s' as a %s, it already exists as a %s", id, dType, aType); registry.propagate(new IllegalStateException(msg)); } }
5,790
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/AbstractTimer.java
/* * Copyright 2014-2023 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; /** * Base class to simplify implementing a {@link Timer}. */ public abstract class AbstractTimer implements Timer { /** Clock to use for measuring the time of calls. */ protected final Clock clock; /** Create a new instance. */ public AbstractTimer(Clock clock) { this.clock = clock; } @Override public Clock clock() { return clock; } }
5,791
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/SwapTimer.java
/* * Copyright 2014-2023 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import com.netflix.spectator.impl.SwapMeter; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.LongSupplier; import java.util.function.Supplier; /** Wraps another timer allowing the underlying type to be swapped. */ final class SwapTimer extends SwapMeter<Timer> implements Timer { /** Create a new instance. */ SwapTimer(Registry registry, LongSupplier versionSupplier, Id id, Timer underlying) { super(registry, versionSupplier, id, underlying); } @Override public Timer lookup() { return registry.timer(id); } @Override public Clock clock() { return registry.clock(); } @Override public void record(long amount, TimeUnit unit) { get().record(amount, unit); } @Override public long count() { return get().count(); } @Override public long totalTime() { return get().totalTime(); } @SuppressWarnings("unchecked") @Override public BatchUpdater batchUpdater(int batchSize) { BatchUpdater updater = get().batchUpdater(batchSize); // Registry implementations can implement `Consumer<Supplier<Timer>>` to allow the // meter to be resolved when flushed and avoid needing to hold on to a particular // instance of the meter that might have expired and been removed from the registry. if (updater instanceof Consumer<?>) { ((Consumer<Supplier<Timer>>) updater).accept(this::get); } return updater; } }
5,792
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/DefaultRegistry.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; /** Default implementation of registry. */ public final class DefaultRegistry extends AbstractRegistry { /** Create a new instance. */ public DefaultRegistry() { this(Clock.SYSTEM); } /** Create a new instance. */ public DefaultRegistry(Clock clock) { super(clock); } /** Create a new instance. */ public DefaultRegistry(Clock clock, RegistryConfig config) { super(clock, config); } @Override protected Counter newCounter(Id id) { return new DefaultCounter(clock(), id); } @Override protected DistributionSummary newDistributionSummary(Id id) { return new DefaultDistributionSummary(clock(), id); } @Override protected Timer newTimer(Id id) { return new DefaultTimer(clock(), id); } @Override protected Gauge newGauge(Id id) { return new DefaultGauge(clock(), id); } @Override protected Gauge newMaxGauge(Id id) { return new DefaultMaxGauge(clock(), id); } /** * Reset the state of this registry. All meters and other associated state will be lost. * Though it is typically recommended to use a new instance for each test, if that is not * possible for some reason, this method can be used to reset the state before a given * unit test. */ @SuppressWarnings("PMD.UselessOverridingMethod") @Override public void reset() { // Overridden to increase visibility from protected in base class to public super.reset(); } }
5,793
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/DistSummaryBatchUpdater.java
/* * Copyright 2014-2022 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; class DistSummaryBatchUpdater implements DistributionSummary.BatchUpdater { private final DistributionSummary distSummary; private final int batchSize; private int count; private final long[] amounts; DistSummaryBatchUpdater(DistributionSummary distSummary, int batchSize) { this.distSummary = distSummary; this.batchSize = batchSize; this.count = 0; this.amounts = new long[batchSize]; } @Override public void record(long amount) { if (amount >= 0) { amounts[count++] = amount; if (count >= batchSize) { flush(); } } } @Override public void flush() { distSummary.record(amounts, count); count = 0; } @Override public void close() throws Exception { flush(); } }
5,794
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/SwapMaxGauge.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import com.netflix.spectator.impl.SwapMeter; import java.util.function.LongSupplier; /** Wraps another gauge allowing the underlying type to be swapped. */ final class SwapMaxGauge extends SwapMeter<Gauge> implements Gauge { /** Create a new instance. */ SwapMaxGauge(Registry registry, LongSupplier versionSupplier, Id id, Gauge underlying) { super(registry, versionSupplier, id, underlying); } @Override public Gauge lookup() { return registry.maxGauge(id); } @Override public void set(double value) { get().set(value); } @Override public double value() { return get().value(); } }
5,795
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/DistributionSummary.java
/* * Copyright 2014-2022 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; /** * Track the sample distribution of events. An example would be the response sizes for requests * hitting and http server. * * <p>The precise set of information maintained depends on the implementation. Most should try to * provide a consistent implementation of {@link #count()} and {@link #totalAmount()}, * but some implementations may not. In particular, the implementation from {@link NoopRegistry} * will always return 0. */ public interface DistributionSummary extends Meter { /** * Updates the statistics kept by the summary with the specified amount. * * @param amount * Amount for an event being measured. For example, if the size in bytes of responses * from a server. If the amount is less than 0 the value will be dropped. */ void record(long amount); /** * Updates the statistics kept by the summary with the specified amounts as a batch. Behaves * as if `record()` was called in a loop, but may be faster in some cases. * * @param amounts * Amounts for an event being measured. For example, if the size in bytes of responses * from a server. If the amount is less than 0 the value will be dropped. * @param n * The number of elements to write from the amounts array (starting from 0). If n is * &lt;= 0 no entries will be recorded. If n is greater than amounts.length, all amounts * will be recorded. * * @see #record(long) */ default void record(long[] amounts, int n) { final int limit = Math.min(amounts.length, n); for (int i = 0; i < limit; i++) { record(amounts[i]); } } /** * The number of times that record has been called since this timer was last reset. * How often a timer is reset depends on the underlying registry implementation. */ long count(); /** * The total amount of all recorded events since this summary was last reset. * How often a timer is reset depends on the underlying registry implementation. */ long totalAmount(); /** * Returns a helper that can be used to more efficiently update the distribution summary * within a single thread. For example, if you need to update a meter within a loop where the * rest of the loop body is fairly cheap, the instrumentation code may add considerable * overhead if done in the loop body. A batched updater can offset a fair amount of that * cost, but the updates may be delayed a bit in reaching the meter. The updates will only * be seen after the updater is explicitly flushed. * * The caller should ensure that the updater is closed after using to guarantee any resources * associated with it are cleaned up. In some cases failure to close the updater could result * in a memory leak. * * @param batchSize * Number of updates to batch before forcing a flush to the meter. * @return * Batch updater implementation for this meter. */ default BatchUpdater batchUpdater(int batchSize) { return new DistSummaryBatchUpdater(this, batchSize); } /** See {@link #batchUpdater(int)}. */ interface BatchUpdater extends AutoCloseable { /** * Updates the statistics kept by the summary with the specified amount. * * @param amount * Amount for an event being measured. For example, if the size in bytes of responses * from a server. If the amount is less than 0 the value will be dropped. */ void record(long amount); /** Push updates to the associated timer. */ void flush(); } }
5,796
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/NoopTimer.java
/* * Copyright 2014-2023 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import java.util.Collections; import java.util.concurrent.TimeUnit; /** Counter implementation for the no-op registry. */ enum NoopTimer implements Timer { /** Singleton instance. */ INSTANCE; @Override public Id id() { return NoopId.INSTANCE; } @Override public boolean hasExpired() { return false; } @Override public void record(long amount, TimeUnit unit) { } @Override public Iterable<Measurement> measure() { return Collections.emptyList(); } @Override public long count() { return 0L; } @Override public long totalTime() { return 0L; } }
5,797
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/Timer.java
/* * Copyright 2014-2023 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import java.time.Duration; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.BinaryOperator; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import java.util.function.DoubleBinaryOperator; import java.util.function.DoubleConsumer; import java.util.function.DoublePredicate; import java.util.function.DoubleSupplier; import java.util.function.DoubleToIntFunction; import java.util.function.DoubleToLongFunction; import java.util.function.DoubleUnaryOperator; import java.util.function.Function; import java.util.function.IntBinaryOperator; import java.util.function.IntConsumer; import java.util.function.IntFunction; import java.util.function.IntPredicate; import java.util.function.IntSupplier; import java.util.function.IntToDoubleFunction; import java.util.function.IntToLongFunction; import java.util.function.IntUnaryOperator; import java.util.function.LongBinaryOperator; import java.util.function.LongConsumer; import java.util.function.LongFunction; import java.util.function.LongPredicate; import java.util.function.LongSupplier; import java.util.function.LongToDoubleFunction; import java.util.function.LongToIntFunction; import java.util.function.LongUnaryOperator; import java.util.function.ObjDoubleConsumer; import java.util.function.ObjIntConsumer; import java.util.function.ObjLongConsumer; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.function.ToDoubleBiFunction; import java.util.function.ToDoubleFunction; import java.util.function.ToIntBiFunction; import java.util.function.ToIntFunction; import java.util.function.ToLongBiFunction; import java.util.function.ToLongFunction; import java.util.function.UnaryOperator; /** * Timer intended to track a large number of short running events. Example would be something like * an http request. Though "short running" is a bit subjective the assumption is that it should be * under a minute. * * <p>The precise set of information maintained by the timer depends on the implementation. Most * should try to provide a consistent implementation of {@link #count()} and {@link #totalTime()}, * but some implementations may not. In particular, the implementation from {@link NoopRegistry} * will always return 0. */ public interface Timer extends Meter { /** * The clock used for timing events. */ default Clock clock() { return Clock.SYSTEM; } /** * Updates the statistics kept by the timer with the specified amount. * * @param amount * Duration of a single event being measured by this timer. If the amount is less than 0 * the value will be dropped. * @param unit * Time unit for the amount being recorded. */ void record(long amount, TimeUnit unit); /** * Updates the statistics kept by the timer with the specified amount. * * @param amount * Duration of a single event being measured by this timer. */ default void record(Duration amount) { record(amount.toNanos(), TimeUnit.NANOSECONDS); } /** * Updates the statistics kept by the timer with the specified amounts. Behaves as if * `record()` was called in a loop, but may be faster in some cases. * * @param amounts * Duration of events being measured by this timer. If the amount is less than 0 * for a value, the value will be dropped. * @param n * The number of elements to write from the amounts array (starting from 0). If n is * &lt;= 0 no entries will be recorded. If n is greater than amounts.length, all amounts * will be recorded. * @param unit * Time unit for the amounts being recorded. * * @see #record(long, TimeUnit) */ default void record(long[] amounts, int n, TimeUnit unit) { final int limit = Math.min(amounts.length, n); for (int i = 0; i < limit; i++) { record(amounts[i], unit); } } /** * Updates the statistics kept by the timer with the specified amounts. Behaves as if * `record()` was called in a loop, but may be faster in some cases. * * @param amounts * Duration of events being measured by this timer. If the amount is less than 0 * for a value, the value will be dropped. * @param n * The number of elements to write from the amounts array (starting from 0). If n is * <= 0 no entries will be recorded. If n is greater than amounts.length, all amounts * will be recorded. * * @see #record(Duration) */ default void record(Duration[] amounts, int n) { final int limit = Math.min(amounts.length, n); for (int i = 0; i < limit; i++) { record(amounts[i]); } } /** * Executes the callable `f` and records the time taken. * * @param f * Function to execute and measure the execution time. * @return * The return value of `f`. * * @deprecated Use {@link #recordCallable(Callable)} instead. */ @Deprecated default <T> T record(Callable<T> f) throws Exception { return recordCallable(f); } /** * Executes the runnable `f` and records the time taken. * * @param f * Function to execute and measure the execution time. * * @deprecated Use {@link #recordRunnable(Runnable)} instead. */ @Deprecated default void record(Runnable f) { recordRunnable(f); } /** * Executes the callable `f` and records the time taken. * * @param f * Function to execute and measure the execution time. * @return * The return value of `f`. */ default <T> T recordCallable(Callable<T> f) throws Exception { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.call(); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } } /** * Executes the runnable `f` and records the time taken. * * @param f * Function to execute and measure the execution time. */ default void recordRunnable(Runnable f) { final Clock clock = clock(); long s = clock.monotonicTime(); try { f.run(); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } } /** * Executes the supplier `f` and records the time taken. * * @param f * Function to execute and measure the execution time. * @return * The return value of `f`. */ default <T> T recordSupplier(Supplier<T> f) { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.get(); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } } /** * Executes the supplier `f` and records the time taken. * * @param f * Function to execute and measure the execution time. * @return * The return value of `f`. */ default boolean recordBooleanSupplier(BooleanSupplier f) { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.getAsBoolean(); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } } /** * Executes the supplier `f` and records the time taken. * * @param f * Function to execute and measure the execution time. * @return * The return value of `f`. */ default double recordDoubleSupplier(DoubleSupplier f) { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.getAsDouble(); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } } /** * Executes the supplier `f` and records the time taken. * * @param f * Function to execute and measure the execution time. * @return * The return value of `f`. */ default int recordIntSupplier(IntSupplier f) { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.getAsInt(); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } } /** * Executes the supplier `f` and records the time taken. * * @param f * Function to execute and measure the execution time. * @return * The return value of `f`. */ default long recordLongSupplier(LongSupplier f) { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.getAsLong(); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default <V> Callable<V> wrapCallable(Callable<V> f) { return () -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.call(); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default Runnable wrapRunnable(Runnable f) { return () -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { f.run(); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default <T, U> BiConsumer<T, U> wrapBiConsumer(BiConsumer<T, U> f) { return (t, u) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { f.accept(t, u); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default <T, U, R> BiFunction<T, U, R> wrapBiFunction(BiFunction<T, U, R> f) { return (t, u) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.apply(t, u); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default <T> BinaryOperator<T> wrapBinaryOperator(BinaryOperator<T> f) { return (t, u) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.apply(t, u); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default <T, U> BiPredicate<T, U> wrapBiPredicate(BiPredicate<T, U> f) { return (t, u) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.test(t, u); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default BooleanSupplier wrapBooleanSupplier(BooleanSupplier f) { return () -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.getAsBoolean(); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default <T> Consumer<T> wrapConsumer(Consumer<T> f) { return (t) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { f.accept(t); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default DoubleBinaryOperator wrapDoubleBinaryOperator(DoubleBinaryOperator f) { return (t, u) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.applyAsDouble(t, u); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default DoubleConsumer wrapDoubleConsumer(DoubleConsumer f) { return (t) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { f.accept(t); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default <R> java.util.function.DoubleFunction<R> wrapDoubleFunction(java.util.function.DoubleFunction<R> f) { return (t) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.apply(t); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default DoublePredicate wrapDoublePredicate(DoublePredicate f) { return (t) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.test(t); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default DoubleSupplier wrapDoubleSupplier(DoubleSupplier f) { return () -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.getAsDouble(); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default DoubleToIntFunction wrapDoubleToIntFunction(DoubleToIntFunction f) { return (t) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.applyAsInt(t); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default DoubleToLongFunction wrapDoubleToLongFunction(DoubleToLongFunction f) { return (t) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.applyAsLong(t); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default DoubleUnaryOperator wrapDoubleUnaryOperator(DoubleUnaryOperator f) { return (t) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.applyAsDouble(t); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default <T, R> Function<T, R> wrapFunction(Function<T, R> f) { return (t) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.apply(t); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default IntBinaryOperator wrapIntBinaryOperator(IntBinaryOperator f) { return (t, u) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.applyAsInt(t, u); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default IntConsumer wrapIntConsumer(IntConsumer f) { return (t) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { f.accept(t); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default <R> IntFunction<R> wrapIntFunction(IntFunction<R> f) { return (t) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.apply(t); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default IntPredicate wrapIntPredicate(IntPredicate f) { return (t) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.test(t); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default IntSupplier wrapIntSupplier(IntSupplier f) { return () -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.getAsInt(); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default IntToDoubleFunction wrapIntToDoubleFunction(IntToDoubleFunction f) { return (t) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.applyAsDouble(t); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default IntToLongFunction wrapIntToLongFunction(IntToLongFunction f) { return (t) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.applyAsLong(t); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default IntUnaryOperator wrapIntUnaryOperator(IntUnaryOperator f) { return (t) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.applyAsInt(t); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default LongBinaryOperator wrapLongBinaryOperator(LongBinaryOperator f) { return (t, u) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.applyAsLong(t, u); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default LongConsumer wrapLongConsumer(LongConsumer f) { return (t) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { f.accept(t); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default <R> LongFunction<R> wrapLongFunction(LongFunction<R> f) { return (t) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.apply(t); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default LongPredicate wrapLongPredicate(LongPredicate f) { return (t) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.test(t); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default LongSupplier wrapLongSupplier(LongSupplier f) { return () -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.getAsLong(); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default LongToIntFunction wrapLongToIntFunction(LongToIntFunction f) { return (t) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.applyAsInt(t); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default LongToDoubleFunction wrapLongToDoubleFunction(LongToDoubleFunction f) { return (t) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.applyAsDouble(t); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default LongUnaryOperator wrapLongUnaryOperator(LongUnaryOperator f) { return (t) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.applyAsLong(t); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default <T> ObjDoubleConsumer<T> wrapObjDoubleConsumer(ObjDoubleConsumer<T> f) { return (t, u) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { f.accept(t, u); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default <T> ObjIntConsumer<T> wrapObjIntConsumer(ObjIntConsumer<T> f) { return (t, u) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { f.accept(t, u); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default <T> ObjLongConsumer<T> wrapObjLongConsumer(ObjLongConsumer<T> f) { return (t, u) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { f.accept(t, u); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default <T> Predicate<T> wrapPredicate(Predicate<T> f) { return (t) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.test(t); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default <T> Supplier<T> wrapSupplier(Supplier<T> f) { return () -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.get(); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default <T, U> ToDoubleBiFunction<T, U> wrapToDoubleBiFunction(ToDoubleBiFunction<T, U> f) { return (t, u) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.applyAsDouble(t, u); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default <T> ToDoubleFunction<T> wrapToDoubleFunction(ToDoubleFunction<T> f) { return (t) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.applyAsDouble(t); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default <T, U> ToIntBiFunction<T, U> wrapToIntBiFunction(ToIntBiFunction<T, U> f) { return (t, u) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.applyAsInt(t, u); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default <T> ToIntFunction<T> wrapToIntFunction(ToIntFunction<T> f) { return (t) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.applyAsInt(t); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default <T, U> ToLongBiFunction<T, U> wrapToLongBiFunction(ToLongBiFunction<T, U> f) { return (t, u) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.applyAsLong(t, u); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default <T> ToLongFunction<T> wrapToLongFunction(ToLongFunction<T> f) { return (t) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.applyAsLong(t); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * Wraps the lambda `f` to update this timer each time the wrapper is invoked. * * @param f * Function to execute and measure the execution time. * @return * Wrapper that invokes `f` and records the time taken. */ default <T> UnaryOperator<T> wrapUnaryOperator(UnaryOperator<T> f) { return (t) -> { final Clock clock = clock(); long s = clock.monotonicTime(); try { return f.apply(t); } finally { long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } /** * The number of times that record has been called since this timer was last reset. * How often a timer is reset depends on the underlying registry implementation. */ long count(); /** * The total time in nanoseconds of all recorded events since this timer was last reset. * How often a timer is reset depends on the underlying registry implementation. */ long totalTime(); /** * Returns a helper that can be used to more efficiently update the timer within a * single thread. For example, if you need to update a meter within a loop where the * rest of the loop body is fairly cheap, the instrumentation code may add considerable * overhead if done in the loop body. A batched updater can offset a fair amount of that * cost, but the updates may be delayed a bit in reaching the meter. The updates will only * be seen after the updater is explicitly flushed. * * <p>The caller should ensure that the updater is closed after using to guarantee any resources * associated with it are cleaned up. In some cases failure to close the updater could result * in a memory leak. * * @param batchSize * Number of updates to batch before forcing a flush to the meter. * @return * Batch updater implementation for this meter. */ default BatchUpdater batchUpdater(int batchSize) { return new TimerBatchUpdater(this, batchSize); } /** See {@link #batchUpdater(int)}. */ interface BatchUpdater extends AutoCloseable { /** * Updates the statistics kept by the timer with the specified amount. * * @param amount * Duration of a single event being measured by this timer. If the amount is less than 0 * the value will be dropped. * @param unit * Time unit for the amount being recorded. */ void record(long amount, TimeUnit unit); /** * Updates the statistics kept by the timer with the specified amount. * * @param amount * Duration of a single event being measured by this timer. */ default void record(Duration amount) { record(amount.toNanos(), TimeUnit.NANOSECONDS); } /** Push updates to the associated timer. */ void flush(); } }
5,798
0
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/DefaultCounter.java
/* * Copyright 2014-2019 Netflix, Inc. * * 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. */ package com.netflix.spectator.api; import com.netflix.spectator.impl.AtomicDouble; import java.util.Collections; /** Counter implementation for the default registry. */ final class DefaultCounter implements Counter { private final Clock clock; private final Id id; private final AtomicDouble count; /** Create a new instance. */ DefaultCounter(Clock clock, Id id) { this.clock = clock; this.id = id; this.count = new AtomicDouble(0.0); } @Override public Id id() { return id; } @Override public boolean hasExpired() { return false; } @Override public Iterable<Measurement> measure() { long now = clock.wallTime(); double v = count.get(); return Collections.singleton(new Measurement(id, now, v)); } @Override public void add(double amount) { if (Double.isFinite(amount) && amount > 0.0) { count.addAndGet(amount); } } @Override public double actualCount() { return count.get(); } }
5,799