Skip to content

Commit

Permalink
feat: Merge main branch features
Browse files Browse the repository at this point in the history
  • Loading branch information
Ahoo-Wang committed Jul 6, 2024
1 parent 841af3b commit f0590ad
Show file tree
Hide file tree
Showing 17 changed files with 141 additions and 110 deletions.
2 changes: 1 addition & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ configure(libraryProjects) {
apply<JavaLibraryPlugin>()
configure<JavaPluginExtension> {
toolchain {
languageVersion.set(JavaLanguageVersion.of(17))
languageVersion.set(JavaLanguageVersion.of(8))
}
withJavadocJar()
withSourcesJar()
Expand Down
5 changes: 3 additions & 2 deletions cosid-core/src/main/java/me/ahoo/cosid/Decorator.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@ public interface Decorator<D> {
*/
@Nonnull
D getActual();

@SuppressWarnings({"unchecked", "rawtypes"})
static <D> D getActual(D any) {
if (any instanceof Decorator decorator) {
if (any instanceof Decorator) {
Decorator decorator = (Decorator) any;
return getActual((D) decorator.getActual());
}
return any;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

package me.ahoo.cosid.accessor.parser;

import com.google.common.collect.Lists;
import me.ahoo.cosid.accessor.IdDefinition;
import me.ahoo.cosid.annotation.AnnotationDefinitionParser;
import me.ahoo.cosid.annotation.entity.IdNotFoundEntity;
Expand All @@ -31,9 +32,10 @@ class CompositeFieldDefinitionParserTest {
@SneakyThrows
@Test
void parse() {
var compositeFieldDefinitionParser = new CompositeFieldDefinitionParser(List.of(AnnotationDefinitionParser.INSTANCE));

CompositeFieldDefinitionParser compositeFieldDefinitionParser = new CompositeFieldDefinitionParser(Lists.newArrayList(AnnotationDefinitionParser.INSTANCE));
Field idField = LongIdEntity.class.getDeclaredField("id");
IdDefinition idDefinition = compositeFieldDefinitionParser.parse(List.of(LongIdEntity.class), idField);
IdDefinition idDefinition = compositeFieldDefinitionParser.parse(Lists.newArrayList(LongIdEntity.class), idField);

Assertions.assertNotEquals(IdDefinition.NOT_FOUND, idDefinition);
Assertions.assertEquals(IdGeneratorProvider.SHARE, idDefinition.getGeneratorName());
Expand All @@ -42,9 +44,9 @@ void parse() {
@SneakyThrows
@Test
void parseIfNotFound() {
var compositeFieldDefinitionParser = new CompositeFieldDefinitionParser(List.of(AnnotationDefinitionParser.INSTANCE));
CompositeFieldDefinitionParser compositeFieldDefinitionParser = new CompositeFieldDefinitionParser(Lists.newArrayList(AnnotationDefinitionParser.INSTANCE));
Field nameField = IdNotFoundEntity.class.getDeclaredField("name");
IdDefinition idDefinition = compositeFieldDefinitionParser.parse(List.of(IdNotFoundEntity.class), nameField);
IdDefinition idDefinition = compositeFieldDefinitionParser.parse(Lists.newArrayList(IdNotFoundEntity.class), nameField);
Assertions.assertEquals(IdDefinition.NOT_FOUND, idDefinition);
}
}
28 changes: 15 additions & 13 deletions cosid-core/src/test/java/me/ahoo/cosid/stat/StatisticalTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

import me.ahoo.cosid.IdGenerator;
import me.ahoo.cosid.converter.Radix62IdConverter;
import me.ahoo.cosid.cosid.Radix36CosIdGenerator;
import me.ahoo.cosid.jvm.UuidGenerator;
Expand All @@ -25,6 +26,7 @@
import me.ahoo.cosid.snowflake.MillisecondSnowflakeId;
import me.ahoo.cosid.snowflake.StringSnowflakeId;
import me.ahoo.cosid.stat.generator.CosIdGeneratorStat;
import me.ahoo.cosid.stat.generator.IdGeneratorStat;
import me.ahoo.cosid.stat.generator.SegmentIdStat;

import me.ahoo.cosid.stat.generator.SimpleIdGeneratorStat;
Expand All @@ -37,51 +39,51 @@ class StatisticalTest {

@Test
void statUuidGenerator() {
var stat = UuidGenerator.INSTANCE.stat();
IdGeneratorStat stat = UuidGenerator.INSTANCE.stat();
Assertions.assertNotNull(stat);
}

@Test
void statSnowflakeId() {
var snowflakeId = new MillisecondSnowflakeId(0);
var stat = snowflakeId.stat();
IdGenerator snowflakeId = new MillisecondSnowflakeId(0);
IdGeneratorStat stat = snowflakeId.stat();
Assertions.assertNotNull(stat);
assertThat(stat, Matchers.instanceOf(SnowflakeIdStat.class));
var snowflakeIdStat = (SnowflakeIdStat) stat;
SnowflakeIdStat snowflakeIdStat = (SnowflakeIdStat) stat;
assertThat(snowflakeIdStat.getMachineId(), equalTo(0));
}

@Test
void statStringSnowflakeId() {
var snowflakeId = new StringSnowflakeId(new MillisecondSnowflakeId(0), Radix62IdConverter.INSTANCE);
var stat = snowflakeId.stat();
IdGenerator snowflakeId = new StringSnowflakeId(new MillisecondSnowflakeId(0), Radix62IdConverter.INSTANCE);
IdGeneratorStat stat = snowflakeId.stat();
Assertions.assertNotNull(stat);
assertThat(stat, Matchers.instanceOf(SimpleIdGeneratorStat.class));
}

@Test
void statSegmentId() {
var segmentId = new DefaultSegmentId(new IdSegmentDistributor.Mock());
var stat = segmentId.stat();
IdGenerator segmentId = new DefaultSegmentId(new IdSegmentDistributor.Mock());
IdGeneratorStat stat = segmentId.stat();
Assertions.assertNotNull(stat);
assertThat(stat, Matchers.instanceOf(SegmentIdStat.class));
}

@Test
void statStringSegmentId() {
var segmentId = new StringSegmentId(new DefaultSegmentId(new IdSegmentDistributor.Mock()), Radix62IdConverter.INSTANCE);
var stat = segmentId.stat();
IdGenerator segmentId = new StringSegmentId(new DefaultSegmentId(new IdSegmentDistributor.Mock()), Radix62IdConverter.INSTANCE);
IdGeneratorStat stat = segmentId.stat();
Assertions.assertNotNull(stat);
assertThat(stat, Matchers.instanceOf(SimpleIdGeneratorStat.class));
}

@Test
void statCosIdGenerator() {
var cosIdGenerator = new Radix36CosIdGenerator(0);
var stat = cosIdGenerator.stat();
IdGenerator cosIdGenerator = new Radix36CosIdGenerator(0);
IdGeneratorStat stat = cosIdGenerator.stat();
Assertions.assertNotNull(stat);
assertThat(stat, Matchers.instanceOf(CosIdGeneratorStat.class));
var cosIdGeneratorStat = (CosIdGeneratorStat) stat;
CosIdGeneratorStat cosIdGeneratorStat = (CosIdGeneratorStat) stat;
assertThat(cosIdGeneratorStat.getMachineId(), equalTo(0));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public void nextMaxIdWhenBack() {

@Test
public void nextMaxIdInParallel() {
var mono = Mono.fromRunnable(() -> {
Mono<Object> mono = Mono.fromRunnable(() -> {
String namespace = MockIdGenerator.INSTANCE.generateAsString();
IdSegmentDistributorDefinition definition = new IdSegmentDistributorDefinition(namespace, "nextMaxIdIParallel", TEST_OFFSET, TEST_STEP);
IdSegmentDistributor distributor = factory().create(definition);
Expand All @@ -84,11 +84,11 @@ public void batchNextMaxId() {
String namespace = MockIdGenerator.INSTANCE.generateAsString();
IdSegmentDistributorDefinition definition = new IdSegmentDistributorDefinition(namespace, "batchNextMaxId", 1, 1);
IdSegmentDistributor distributor = factory().create(definition);
var segmentChainId = new SegmentChainId(distributor);
SegmentChainId segmentChainId = new SegmentChainId(distributor);
for (int i = 0; i < 1000; i++) {
segmentChainId.generateAsString();
}
var mono = Mono.fromRunnable(() -> {
Mono<Object> mono = Mono.fromRunnable(() -> {
for (int i = 0; i < 1000; i++) {
segmentChainId.generateAsString();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package me.ahoo.cosid.mybatis;

import com.google.common.collect.Lists;
import me.ahoo.cosid.accessor.parser.DefaultAccessorParser;
import me.ahoo.cosid.accessor.registry.DefaultAccessorRegistry;
import me.ahoo.cosid.annotation.AnnotationDefinitionParser;
Expand Down Expand Up @@ -181,12 +182,12 @@ public int update(MappedStatement ms, Object parameter) throws SQLException {

@Override
public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey cacheKey, BoundSql boundSql) throws SQLException {
return List.of();
return Lists.newArrayList();
}

@Override
public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
return List.of();
return Lists.newArrayList();
}

@Override
Expand All @@ -196,7 +197,7 @@ public <E> Cursor<E> queryCursor(MappedStatement ms, Object parameter, RowBounds

@Override
public List<BatchResult> flushStatements() throws SQLException {
return List.of();
return Lists.newArrayList();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,39 +45,39 @@
*/
@Slf4j
public class ProxyMachineIdDistributor extends AbstractMachineIdDistributor {

private final OkHttpClient client;

private final String proxyHost;

public ProxyMachineIdDistributor(OkHttpClient client, String proxyHost, MachineStateStorage machineStateStorage, ClockBackwardsSynchronizer clockBackwardsSynchronizer) {
super(machineStateStorage, clockBackwardsSynchronizer);
this.client = client;
this.proxyHost = proxyHost;
}

@SneakyThrows
@Override
protected MachineState distributeRemote(String namespace, int machineBit, InstanceId instanceId, Duration safeGuardDuration) {
String apiUrl =
Strings.lenientFormat("%s/machines/%s?instanceId=%s&stable=%s&machineBit=%s&safeGuardDuration=%s", proxyHost, namespace, instanceId.getInstanceId(), instanceId.isStable(), machineBit,
safeGuardDuration);
Strings.lenientFormat("%s/machines/%s?instanceId=%s&stable=%s&machineBit=%s&safeGuardDuration=%s", proxyHost, namespace, instanceId.getInstanceId(), instanceId.isStable(), machineBit,
safeGuardDuration);
if (log.isInfoEnabled()) {
log.info("Distribute Remote instanceId:[{}] - machineBit:[{}] @ namespace:[{}] - apiUrl:[{}].", instanceId, machineBit, namespace, apiUrl);
}

Request request = new Request.Builder()
.url(apiUrl)
.post(Util.EMPTY_REQUEST)
.build();
.url(apiUrl)
.post(Util.EMPTY_REQUEST)
.build();
try (Response response = client.newCall(request).execute()) {
ResponseBody responseBody = response.body();
assert responseBody != null;
String bodyStr = responseBody.string();
if (log.isInfoEnabled()) {
log.info("Distribute Remote instanceId:[{}] - machineBit:[{}] @ namespace:[{}] - response:[{}].", instanceId, machineBit, namespace, bodyStr);
}

if (response.isSuccessful()) {
return Jsons.OBJECT_MAPPER.readValue(bodyStr, MachineStateDto.class);
}
Expand All @@ -88,19 +88,19 @@ protected MachineState distributeRemote(String namespace, int machineBit, Instan
throw new IllegalStateException(Strings.lenientFormat("Unexpected code:[%s] - message:[%s].", errorResponse.getCode(), errorResponse.getMsg()));
}
}

@SneakyThrows
@Override
protected void revertRemote(String namespace, InstanceId instanceId, MachineState machineState) {
String apiUrl = Strings.lenientFormat("%s/machines/%s?instanceId=%s&stable=%s", proxyHost, namespace, instanceId.getInstanceId(), instanceId.isStable());
if (log.isInfoEnabled()) {
log.info("Revert Remote [{}] instanceId:[{}] @ namespace:[{}] - apiUrl:[{}].", machineState, instanceId, namespace, apiUrl);
}

Request request = new Request.Builder()
.url(apiUrl)
.delete()
.build();
.url(apiUrl)
.delete()
.build();
try (Response response = client.newCall(request).execute()) {
if (log.isInfoEnabled()) {
ResponseBody responseBody = response.body();
Expand All @@ -110,21 +110,21 @@ protected void revertRemote(String namespace, InstanceId instanceId, MachineStat
}
}
}

@SneakyThrows
@Override
protected void guardRemote(String namespace, InstanceId instanceId, MachineState machineState, Duration safeGuardDuration) {
String apiUrl =
Strings.lenientFormat("%s/machines/%s?instanceId=%s&stable=%s&safeGuardDuration=%s", proxyHost, namespace, instanceId.getInstanceId(), instanceId.isStable(), safeGuardDuration);
Strings.lenientFormat("%s/machines/%s?instanceId=%s&stable=%s&safeGuardDuration=%s", proxyHost, namespace, instanceId.getInstanceId(), instanceId.isStable(), safeGuardDuration);

if (log.isInfoEnabled()) {
log.info("Guard Remote [{}] instanceId:[{}] @ namespace:[{}] - apiUrl:[{}].", machineState, instanceId, namespace, apiUrl);
}

Request request = new Request.Builder()
.url(apiUrl)
.patch(Util.EMPTY_REQUEST)
.build();
.url(apiUrl)
.patch(Util.EMPTY_REQUEST)
.build();
try (Response response = client.newCall(request).execute()) {
ResponseBody responseBody = response.body();
assert responseBody != null;
Expand All @@ -135,14 +135,17 @@ protected void guardRemote(String namespace, InstanceId instanceId, MachineState
if (response.isSuccessful()) {
return;
}

ErrorResponse errorResponse = Jsons.OBJECT_MAPPER.readValue(bodyStr, ErrorResponse.class);
switch (errorResponse.getCode()) {
case NOT_FOUND_MACHINE_STATE -> throw new NotFoundMachineStateException(namespace, instanceId);
case MACHINE_ID_LOST -> throw new MachineIdLostException(namespace, instanceId, machineState);
default -> throw new IllegalStateException("Unexpected value: " + errorResponse.getCode());
case NOT_FOUND_MACHINE_STATE:
throw new NotFoundMachineStateException(namespace, instanceId);
case MACHINE_ID_LOST:
throw new MachineIdLostException(namespace, instanceId, machineState);
default:
throw new IllegalStateException("Unexpected value: " + errorResponse.getCode());
}
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,23 @@ protected IdConverterDecorator(T idGenerator, IdConverterDefinition converterDef
public T decorate() {
IdConverter idConverter = ToStringIdConverter.INSTANCE;
switch (converterDefinition.getType()) {
case TO_STRING -> idConverter = newToString(idConverter);
case RADIX -> idConverter = newRadix();
case RADIX36 -> idConverter = newRadix36();
case SNOWFLAKE_FRIENDLY -> idConverter = newSnowflakeFriendly();
case CUSTOM -> idConverter = newCustom();
default -> throw new IllegalStateException("Unexpected value: " + converterDefinition.getType());
case TO_STRING:
idConverter = newToString(idConverter);
break;
case RADIX:
idConverter = newRadix();
break;
case RADIX36:
idConverter = newRadix36();
break;
case SNOWFLAKE_FRIENDLY:
idConverter = newSnowflakeFriendly();
break;
case CUSTOM:
idConverter = newCustom();
break;
default:
throw new IllegalStateException("Unexpected value: " + converterDefinition.getType());
}

IdConverterDefinition.GroupPrefix groupPrefix = converterDefinition.getGroupPrefix();
Expand Down Expand Up @@ -103,7 +114,8 @@ protected IdConverter newCustom() {
IdConverterDefinition.Custom custom = converterDefinition.getCustom();
try {
return custom.getType().getConstructor().newInstance();
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
} catch (InstantiationException | IllegalAccessException | InvocationTargetException
| NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,21 +38,21 @@ public CosIdEndpoint(IdGeneratorProvider idGeneratorProvider) {
public Map<String, IdGeneratorStat> stat() {
Map<String, IdGeneratorStat> statMap = new HashMap<>();
for (Map.Entry<String, IdGenerator> entry : idGeneratorProvider.entries()) {
var stat = entry.getValue().stat();
IdGeneratorStat stat = entry.getValue().stat();
statMap.put(entry.getKey(), stat);
}
return statMap;
}

@ReadOperation
public IdGeneratorStat getStat(@Selector String name) {
var idGenerator = idGeneratorProvider.getRequired(name);
IdGenerator idGenerator = idGeneratorProvider.getRequired(name);
return idGenerator.stat();
}

@DeleteOperation
public IdGeneratorStat remove(@Selector String name) {
var idGenerator = idGeneratorProvider.remove(name);
IdGenerator idGenerator = idGeneratorProvider.remove(name);
return idGenerator.stat();
}

Expand Down
Loading

0 comments on commit f0590ad

Please sign in to comment.