diff --git a/.checkstyle/suppressions.xml b/.checkstyle/suppressions.xml index f8138959..e786a7e7 100644 --- a/.checkstyle/suppressions.xml +++ b/.checkstyle/suppressions.xml @@ -35,4 +35,6 @@ checks="MissingJavadocPackage"/> + diff --git a/.gitignore b/.gitignore index f3a8b38e..492c9f19 100644 --- a/.gitignore +++ b/.gitignore @@ -82,3 +82,4 @@ gradle-app.setting .DS_Store **/run/ +**/run2/ diff --git a/build-logic/src/main/kotlin/carbon.base-conventions.gradle.kts b/build-logic/src/main/kotlin/carbon.base-conventions.gradle.kts index ba901843..a5b494de 100644 --- a/build-logic/src/main/kotlin/carbon.base-conventions.gradle.kts +++ b/build-logic/src/main/kotlin/carbon.base-conventions.gradle.kts @@ -23,6 +23,7 @@ license { exclude("net/draycia/carbon/common/command/argument/OptionValueParser.java") exclude("net/draycia/carbon/common/messages/PrefixedDelegateIterator.java") exclude("net/draycia/carbon/common/messages/StandardPlaceholderResolverStrategyButDifferent.java") + exclude("com/google/inject/assistedinject") } tasks { diff --git a/common/src/main/java/com/google/inject/assistedinject/FactoryProvider3.java b/common/src/main/java/com/google/inject/assistedinject/FactoryProvider3.java new file mode 100644 index 00000000..a43b6d90 --- /dev/null +++ b/common/src/main/java/com/google/inject/assistedinject/FactoryProvider3.java @@ -0,0 +1,1135 @@ +/* + * Copyright (C) 2008 Google 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.google.inject.assistedinject; + +import static com.google.common.base.Preconditions.checkState; +import static com.google.common.collect.Iterables.getOnlyElement; + +import com.google.common.base.MoreObjects; +import com.google.common.base.Objects; +import com.google.common.collect.HashMultimap; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import com.google.common.collect.Multimap; +import com.google.common.collect.Sets; +import com.google.inject.AbstractModule; +import com.google.inject.Binder; +import com.google.inject.Binding; +import com.google.inject.ConfigurationException; +import com.google.inject.Inject; +import com.google.inject.Injector; +import com.google.inject.Key; +import com.google.inject.Module; +import com.google.inject.Provider; +import com.google.inject.ProvisionException; +import com.google.inject.Scopes; +import com.google.inject.TypeLiteral; +import com.google.inject.internal.Annotations; +import com.google.inject.internal.Errors; +import com.google.inject.internal.ErrorsException; +import com.google.inject.internal.UniqueAnnotations; +import com.google.inject.internal.util.Classes; +import com.google.inject.spi.BindingTargetVisitor; +import com.google.inject.spi.Dependency; +import com.google.inject.spi.HasDependencies; +import com.google.inject.spi.InjectionPoint; +import com.google.inject.spi.Message; +import com.google.inject.spi.ProviderInstanceBinding; +import com.google.inject.spi.ProviderWithExtensionVisitor; +import com.google.inject.spi.Toolable; +import com.google.inject.util.Providers; +import java.lang.annotation.Annotation; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.lang.reflect.Proxy; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * The newer implementation of factory provider. This implementation uses a child injector to create + * values. + * + *

Carbon - modified from FactoryProvider2 for default method support

+ * + * @author jessewilson@google.com (Jesse Wilson) + * @author dtm@google.com (Daniel Martin) + * @author schmitt@google.com (Peter Schmitt) + * @author sameb@google.com (Sam Berlin) + */ +public final class FactoryProvider3 // Carbon - public + implements InvocationHandler, + ProviderWithExtensionVisitor, + HasDependencies, + AssistedInjectBinding { + + /** A constant annotation to denote the return value, instead of creating a new one each time. */ + static final Annotation RETURN_ANNOTATION = UniqueAnnotations.create(); + + // use the logger under a well-known name, not FactoryProvider2 + static final Logger logger = Logger.getLogger(AssistedInject.class.getName()); + + /** + * A constant that determines if we allow fallback to using the JDK internals to make a "private + * lookup". Typically always true, but reflectively set to false in tests. + */ + @SuppressWarnings("FieldCanBeFinal") // non-final for testing + private static boolean allowPrivateLookupFallback = true; + + /** + * A constant that determines if we allow fallback to using method handle workarounds (if + * required). Typically always true, but reflectively set to false in tests. + */ + @SuppressWarnings("FieldCanBeFinal") // non-final for testing + private static boolean allowMethodHandleWorkaround = true; + + /** if a factory method parameter isn't annotated, it gets this annotation. */ + static final Assisted DEFAULT_ANNOTATION = + new Assisted() { + @Override + public String value() { + return ""; + } + + @Override + public Class annotationType() { + return Assisted.class; + } + + @Override + public boolean equals(Object o) { + return o instanceof Assisted && ((Assisted) o).value().isEmpty(); + } + + @Override + public int hashCode() { + return 127 * "value".hashCode() ^ "".hashCode(); + } + + @Override + public String toString() { + return "@" + + Assisted.class.getName() + + "(" + + Annotations.memberValueString("value", "") + + ")"; + } + }; + + /** All the data necessary to perform an assisted inject. */ + private static class AssistData implements AssistedMethod { + /** the constructor the implementation is constructed with. */ + final Constructor constructor; + /** the return type in the factory method that the constructor is bound to. */ + final Key returnType; + /** the parameters in the factory method associated with this data. */ + final ImmutableList> paramTypes; + /** the type of the implementation constructed */ + final TypeLiteral implementationType; + + /** All non-assisted dependencies required by this method. */ + final Set> dependencies; + /** The factory method associated with this data */ + final Method factoryMethod; + + /** true if {@link #isValidForOptimizedAssistedInject} returned true. */ + final boolean optimized; + /** the list of optimized providers, empty if not optimized. */ + final List providers; + /** used to perform optimized factory creations. */ + volatile Binding cachedBinding; // TODO: volatile necessary? + + AssistData( + Constructor constructor, + Key returnType, + ImmutableList> paramTypes, + TypeLiteral implementationType, + Method factoryMethod, + Set> dependencies, + boolean optimized, + List providers) { + this.constructor = constructor; + this.returnType = returnType; + this.paramTypes = paramTypes; + this.implementationType = implementationType; + this.factoryMethod = factoryMethod; + this.dependencies = dependencies; + this.optimized = optimized; + this.providers = providers; + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(getClass()) + .add("ctor", constructor) + .add("return type", returnType) + .add("param type", paramTypes) + .add("implementation type", implementationType) + .add("dependencies", dependencies) + .add("factory method", factoryMethod) + .add("optimized", optimized) + .add("providers", providers) + .add("cached binding", cachedBinding) + .toString(); + } + + @Override + public Set> getDependencies() { + return dependencies; + } + + @Override + public Method getFactoryMethod() { + return factoryMethod; + } + + @Override + public Constructor getImplementationConstructor() { + return constructor; + } + + @Override + public TypeLiteral getImplementationType() { + return implementationType; + } + } + + /** Mapping from method to the data about how the method will be assisted. */ + private final ImmutableMap assistDataByMethod; + + /** Mapping from method to method handle, for generated default methods. */ + private final ImmutableMap methodHandleByMethod; + + /** the hosting injector, or null if we haven't been initialized yet */ + private Injector injector; + + /** the factory interface, implemented and provided */ + private final F factory; + + /** The key that this is bound to. */ + private final Key factoryKey; + + /** The binding collector, for equality/hashing purposes. */ + private final BindingCollector collector; + + /** + * Utility class for collecting factory bindings. Used for configuring {@link FactoryProvider3}. + * + * @author schmitt@google.com (Peter Schmitt) + */ + static class BindingCollector { + + private final Map, TypeLiteral> bindings = new HashMap<>(); + + public BindingCollector addBinding(Key key, TypeLiteral target) { + if (bindings.containsKey(key)) { + throw new ConfigurationException( + ImmutableSet.of(new Message("Only one implementation can be specified for " + key))); + } + + bindings.put(key, target); + + return this; + } + + public Map, TypeLiteral> getBindings() { + return Collections.unmodifiableMap(bindings); + } + + @Override + public int hashCode() { + return bindings.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return (obj instanceof BindingCollector) && bindings.equals(((BindingCollector) obj).bindings); + } + } + + /** + * @param factoryKey a key for a Java interface that defines one or more create methods. + * @param collector binding configuration that maps method return types to implementation types. + * @param userLookups user provided lookups, optional. + */ + public FactoryProvider3( + Key factoryKey, BindingCollector collector, MethodHandles.Lookup userLookups) { + this.factoryKey = factoryKey; + this.collector = collector == null ? new BindingCollector() : collector; collector = this.collector; // Carbon + + TypeLiteral factoryType = factoryKey.getTypeLiteral(); + Errors errors = new Errors(); + + @SuppressWarnings("unchecked") // we imprecisely treat the class literal of T as a Class + Class factoryRawType = (Class) (Class) factoryType.getRawType(); + + try { + if (!factoryRawType.isInterface()) { + throw errors.addMessage("%s must be an interface.", factoryRawType).toException(); + } + + Multimap defaultMethods = HashMultimap.create(); + Multimap otherMethods = HashMultimap.create(); + ImmutableMap.Builder assistDataBuilder = ImmutableMap.builder(); + // TODO: also grab methods from superinterfaces + for (Method method : factoryRawType.getMethods()) { + // Skip static methods + if (Modifier.isStatic(method.getModifiers())) { + continue; + } + + // Skip default methods that java8 may have created. + if (method.isDefault()/*isDefault(method) && (method.isBridge() || method.isSynthetic())*/) { // Carbon - allow non-generated default methods + // Even synthetic default methods need the return type validation... + // unavoidable consequence of javac8. :-( + validateFactoryReturnType(errors, method.getReturnType(), factoryRawType); + defaultMethods.put(method.getName(), method); + continue; + } + otherMethods.put(method.getName(), method); + + TypeLiteral returnTypeLiteral = factoryType.getReturnType(method); + Key returnType; + try { + returnType = + Annotations.getKey(returnTypeLiteral, method, method.getAnnotations(), errors); + } catch (ConfigurationException ce) { + // If this was an error due to returnTypeLiteral not being specified, rephrase + // it as our factory not being specified, so it makes more sense to users. + if (isTypeNotSpecified(returnTypeLiteral, ce)) { + throw errors.keyNotFullySpecified(TypeLiteral.get(factoryRawType)).toException(); + } else { + throw ce; + } + } + validateFactoryReturnType(errors, returnType.getTypeLiteral().getRawType(), factoryRawType); + List> params = factoryType.getParameterTypes(method); + Annotation[][] paramAnnotations = method.getParameterAnnotations(); + int p = 0; + List> keys = Lists.newArrayList(); + for (TypeLiteral param : params) { + Key paramKey = Annotations.getKey(param, method, paramAnnotations[p++], errors); + Class underlylingType = paramKey.getTypeLiteral().getRawType(); + if (underlylingType.equals(Provider.class) + || underlylingType.equals(javax.inject.Provider.class)) { + errors.addMessage( + "A Provider may not be a type in a factory method of an AssistedInject." + + "\n Offending instance is parameter [%s] with key [%s] on method [%s]", + p, paramKey, method); + } + keys.add(assistKey(method, paramKey, errors)); + } + ImmutableList> immutableParamList = ImmutableList.copyOf(keys); + + // try to match up the method to the constructor + TypeLiteral implementation = collector.getBindings().get(returnType); + if (implementation == null) { + implementation = returnType.getTypeLiteral(); + } + Class scope = + Annotations.findScopeAnnotation(errors, implementation.getRawType()); + if (scope != null) { + errors.addMessage( + "Found scope annotation [%s] on implementation class " + + "[%s] of AssistedInject factory [%s].\nThis is not allowed, please" + + " remove the scope annotation.", + scope, implementation.getRawType(), factoryType); + } + + InjectionPoint ctorInjectionPoint; + try { + ctorInjectionPoint = + findMatchingConstructorInjectionPoint( + method, returnType, implementation, immutableParamList); + } catch (ErrorsException ee) { + errors.merge(ee.getErrors()); + continue; + } + + Constructor constructor = (Constructor) ctorInjectionPoint.getMember(); + List providers = Collections.emptyList(); + Set> deps = getDependencies(ctorInjectionPoint, implementation); + boolean optimized = false; + // Now go through all dependencies of the implementation and see if it is OK to + // use an optimized form of assistedinject2. The optimized form requires that + // all injections directly inject the object itself (and not a Provider of the object, + // or an Injector), because it caches a single child injector and mutates the Provider + // of the arguments in a ThreadLocal. + if (isValidForOptimizedAssistedInject(deps, implementation.getRawType(), factoryType)) { + ImmutableList.Builder providerListBuilder = ImmutableList.builder(); + for (int i = 0; i < params.size(); i++) { + providerListBuilder.add(new ThreadLocalProvider()); + } + providers = providerListBuilder.build(); + optimized = true; + } + + AssistData data = + new AssistData( + constructor, + returnType, + immutableParamList, + implementation, + method, + removeAssistedDeps(deps), + optimized, + providers); + assistDataBuilder.put(method, data); + } + + factory = + factoryRawType.cast( + Proxy.newProxyInstance( + factoryRawType.getClassLoader(), new Class[] {factoryRawType}, this)); + + // Now go back through default methods. Try to use MethodHandles to make things + // work. If that doesn't work, fallback to trying to find compatible method + // signatures. + Map dataSoFar = assistDataBuilder.build(); + ImmutableMap.Builder methodHandleBuilder = ImmutableMap.builder(); + boolean warnedAboutUserLookups = false; + for (Map.Entry entry : defaultMethods.entries()) { + if (!warnedAboutUserLookups + && userLookups == null + && !Modifier.isPublic(factory.getClass().getModifiers())) { + warnedAboutUserLookups = true; + logger.log( + Level.WARNING, + "AssistedInject factory {0} is non-public and has default methods. " // Carbon - adjust message + + " Please pass a `MethodHandles.lookup()` with" + + " FactoryModuleBuilder.withLookups when using this factory so that Guice can" + + " properly call the default methods. Guice will try to workaround this, but " + + "it does not always work (depending on the method signatures of the factory).", + new Object[] {factoryType}); + } + + // Note: If the user didn't supply a valid lookup, we always try to fallback to the hacky + // signature comparing workaround below. + // This is because all these shenanigans are only necessary because we're implementing + // AssistedInject through a Proxy. If we were to generate a subclass (which we theoretically + // _could_ do), then we wouldn't inadvertantly proxy the javac-generated default methods + // too (and end up with a stack overflow from infinite recursion). + // As such, we try our hardest to "make things work" requiring requiring extra effort from + // the user. + + Method defaultMethod = entry.getValue(); + MethodHandle handle = null; + try { + handle = + superMethodHandle( + SuperMethodSupport.METHOD_LOOKUP, defaultMethod, factory, userLookups); + } catch (ReflectiveOperationException e1) { + // If the user-specified lookup failed, try again w/ the private lookup hack. + // If _that_ doesn't work, try the below workaround. + if (allowPrivateLookupFallback + && SuperMethodSupport.METHOD_LOOKUP != SuperMethodLookup.PRIVATE_LOOKUP) { + try { + handle = + superMethodHandle( + SuperMethodLookup.PRIVATE_LOOKUP, defaultMethod, factory, userLookups); + } catch (ReflectiveOperationException e2) { + // ignored, use below workaround. + } + } + } + + Supplier failureMsg = + () -> + "Unable to use non-public factory " + + factoryRawType.getName() + + ". Please call" + + " FactoryModuleBuilder.withLookups(MethodHandles.lookup()) (with a" + + " lookups that has access to the factory), or make the factory" + + " public."; + if (handle != null) { + methodHandleBuilder.put(defaultMethod, handle); + } else if (!allowMethodHandleWorkaround) { + errors.addMessage(failureMsg.get()); + } else { + boolean foundMatch = false; + for (Method otherMethod : otherMethods.get(defaultMethod.getName())) { + if (dataSoFar.containsKey(otherMethod) && isCompatible(defaultMethod, otherMethod)) { + if (foundMatch) { + errors.addMessage(failureMsg.get()); + break; + } else { + assistDataBuilder.put(defaultMethod, dataSoFar.get(otherMethod)); + foundMatch = true; + } + } + } + // We always expect to find at least one match, because we only deal with javac-generated + // default methods. If we ever allow user-specified default methods, this will need to + // change. + if (!foundMatch) { + throw new IllegalStateException("Can't find method compatible with: " + defaultMethod); + } + } + } + + // If we generated any errors (from finding matching constructors, for instance), throw an + // exception. + if (errors.hasErrors()) { + throw errors.toException(); + } + + assistDataByMethod = assistDataBuilder.build(); + methodHandleByMethod = methodHandleBuilder.build(); + } catch (ErrorsException e) { + throw new ConfigurationException(e.getErrors().getMessages()); + } + } + + static boolean isDefault(Method method) { + // Per the javadoc, default methods are non-abstract, public, non-static. + // They're also in interfaces, but we can guarantee that already since we only act + // on interfaces. + return (method.getModifiers() & (Modifier.ABSTRACT | Modifier.PUBLIC | Modifier.STATIC)) + == Modifier.PUBLIC; + } + + private boolean isCompatible(Method src, Method dst) { + if (!src.getReturnType().isAssignableFrom(dst.getReturnType())) { + return false; + } + Class[] srcParams = src.getParameterTypes(); + Class[] dstParams = dst.getParameterTypes(); + if (srcParams.length != dstParams.length) { + return false; + } + for (int i = 0; i < srcParams.length; i++) { + if (!srcParams[i].isAssignableFrom(dstParams[i])) { + return false; + } + } + return true; + } + + @Override + public F get() { + return factory; + } + + @Override + public Set> getDependencies() { + Set> combinedDeps = new HashSet<>(); + for (AssistData data : assistDataByMethod.values()) { + combinedDeps.addAll(data.dependencies); + } + return ImmutableSet.copyOf(combinedDeps); + } + + @Override + public Key getKey() { + return factoryKey; + } + + // Safe cast because values are typed to AssistedData, which is an AssistedMethod, and + // the collection is immutable. + @Override + @SuppressWarnings("unchecked") + public Collection getAssistedMethods() { + return (Collection) (Collection) assistDataByMethod.values(); + } + + @Override + @SuppressWarnings("unchecked") + public V acceptExtensionVisitor( + BindingTargetVisitor visitor, ProviderInstanceBinding binding) { + if (visitor instanceof AssistedInjectTargetVisitor) { + return ((AssistedInjectTargetVisitor) visitor).visit((AssistedInjectBinding) this); + } + return visitor.visit(binding); + } + + private void validateFactoryReturnType(Errors errors, Class returnType, Class factoryType) { + if (Modifier.isPublic(factoryType.getModifiers()) + && !Modifier.isPublic(returnType.getModifiers())) { + errors.addMessage( + "%s is public, but has a method that returns a non-public type: %s. " + + "Due to limitations with java.lang.reflect.Proxy, this is not allowed. " + + "Please either make the factory non-public or the return type public.", + factoryType, returnType); + } + } + + /** + * Returns true if the ConfigurationException is due to an error of TypeLiteral not being fully + * specified. + */ + private boolean isTypeNotSpecified(TypeLiteral typeLiteral, ConfigurationException ce) { + Collection messages = ce.getErrorMessages(); + if (messages.size() == 1) { + Message msg = + Iterables.getOnlyElement(new Errors().keyNotFullySpecified(typeLiteral).getMessages()); + return msg.getMessage().equals(Iterables.getOnlyElement(messages).getMessage()); + } else { + return false; + } + } + + /** + * Finds a constructor suitable for the method. If the implementation contained any constructors + * marked with {@link AssistedInject}, this requires all {@link Assisted} parameters to exactly + * match the parameters (in any order) listed in the method. Otherwise, if no {@link + * AssistedInject} constructors exist, this will default to looking for an {@literal @}{@link + * Inject} constructor. + */ + private InjectionPoint findMatchingConstructorInjectionPoint( + Method method, Key returnType, TypeLiteral implementation, List> paramList) + throws ErrorsException { + Errors errors = new Errors(method); + if (returnType.getTypeLiteral().equals(implementation)) { + errors = errors.withSource(implementation); + } else { + errors = errors.withSource(returnType).withSource(implementation); + } + + Class rawType = implementation.getRawType(); + if (Modifier.isInterface(rawType.getModifiers())) { + errors.addMessage( + "%s is an interface, not a concrete class. Unable to create AssistedInject factory.", + implementation); + throw errors.toException(); + } else if (Modifier.isAbstract(rawType.getModifiers())) { + errors.addMessage( + "%s is abstract, not a concrete class. Unable to create AssistedInject factory.", + implementation); + throw errors.toException(); + } else if (Classes.isInnerClass(rawType)) { + errors.cannotInjectInnerClass(rawType); + throw errors.toException(); + } + + Constructor matchingConstructor = null; + boolean anyAssistedInjectConstructors = false; + // Look for AssistedInject constructors... + for (Constructor constructor : rawType.getDeclaredConstructors()) { + if (constructor.isAnnotationPresent(AssistedInject.class)) { + anyAssistedInjectConstructors = true; + if (constructorHasMatchingParams(implementation, constructor, paramList, errors)) { + if (matchingConstructor != null) { + errors.addMessage( + "%s has more than one constructor annotated with @AssistedInject" + + " that matches the parameters in method %s. Unable to create " + + "AssistedInject factory.", + implementation, method); + throw errors.toException(); + } else { + matchingConstructor = constructor; + } + } + } + } + + if (!anyAssistedInjectConstructors) { + // If none existed, use @Inject or a no-arg constructor. + try { + return InjectionPoint.forConstructorOf(implementation); + } catch (ConfigurationException e) { + errors.merge(e.getErrorMessages()); + throw errors.toException(); + } + } else { + // Otherwise, use it or fail with a good error message. + if (matchingConstructor != null) { + // safe because we got the constructor from this implementation. + @SuppressWarnings("unchecked") + InjectionPoint ip = + InjectionPoint.forConstructor( + (Constructor) matchingConstructor, implementation); + return ip; + } else { + errors.addMessage( + "%s has @AssistedInject constructors, but none of them match the" + + " parameters in method %s. Unable to create AssistedInject factory.", + implementation, method); + throw errors.toException(); + } + } + } + + /** + * Matching logic for constructors annotated with AssistedInject. This returns true if and only if + * all @Assisted parameters in the constructor exactly match (in any order) all @Assisted + * parameters the method's parameter. + */ + private boolean constructorHasMatchingParams( + TypeLiteral type, Constructor constructor, List> paramList, Errors errors) + throws ErrorsException { + List> params = type.getParameterTypes(constructor); + Annotation[][] paramAnnotations = constructor.getParameterAnnotations(); + int p = 0; + List> constructorKeys = Lists.newArrayList(); + for (TypeLiteral param : params) { + Key paramKey = Annotations.getKey(param, constructor, paramAnnotations[p++], errors); + constructorKeys.add(paramKey); + } + // Require that every key exist in the constructor to match up exactly. + for (Key key : paramList) { + // If it didn't exist in the constructor set, we can't use it. + if (!constructorKeys.remove(key)) { + return false; + } + } + // If any keys remain and their annotation is Assisted, we can't use it. + for (Key key : constructorKeys) { + if (key.getAnnotationType() == Assisted.class) { + return false; + } + } + // All @Assisted params match up to the method's parameters. + return true; + } + + /** Calculates all dependencies required by the implementation and constructor. */ + private Set> getDependencies( + InjectionPoint ctorPoint, TypeLiteral implementation) { + ImmutableSet.Builder> builder = ImmutableSet.builder(); + builder.addAll(ctorPoint.getDependencies()); + if (!implementation.getRawType().isInterface()) { + for (InjectionPoint ip : InjectionPoint.forInstanceMethodsAndFields(implementation)) { + builder.addAll(ip.getDependencies()); + } + } + return builder.build(); + } + + /** Return all non-assisted dependencies. */ + private Set> removeAssistedDeps(Set> deps) { + ImmutableSet.Builder> builder = ImmutableSet.builder(); + for (Dependency dep : deps) { + Class annotationType = dep.getKey().getAnnotationType(); + if (annotationType == null || !annotationType.equals(Assisted.class)) { + builder.add(dep); + } + } + return builder.build(); + } + + /** + * Returns true if all dependencies are suitable for the optimized version of AssistedInject. The + * optimized version caches the binding and uses a ThreadLocal Provider, so can only be applied if + * the assisted bindings are immediately provided. This looks for hints that the values may be + * lazily retrieved, by looking for injections of Injector or a Provider for the assisted values. + */ + private boolean isValidForOptimizedAssistedInject( + Set> dependencies, Class implementation, TypeLiteral factoryType) { + Set> badDeps = null; // optimization: create lazily + for (Dependency dep : dependencies) { + if (isInjectorOrAssistedProvider(dep)) { + if (badDeps == null) { + badDeps = Sets.newHashSet(); + } + badDeps.add(dep); + } + } + if (badDeps != null && !badDeps.isEmpty()) { + logger.log( + Level.WARNING, + "AssistedInject factory {0} will be slow " + + "because {1} has assisted Provider dependencies or injects the Injector. " + + "Stop injecting @Assisted Provider (instead use @Assisted T) " + + "or Injector to speed things up. (It will be a ~6500% speed bump!) " + + "The exact offending deps are: {2}", + new Object[] {factoryType, implementation, badDeps}); + return false; + } + return true; + } + + /** + * Returns true if the dependency is for {@link Injector} or if the dependency is a {@link + * Provider} for a parameter that is {@literal @}{@link Assisted}. + */ + private boolean isInjectorOrAssistedProvider(Dependency dependency) { + Class annotationType = dependency.getKey().getAnnotationType(); + if (annotationType != null && annotationType.equals(Assisted.class)) { // If it's assisted.. + if (dependency + .getKey() + .getTypeLiteral() + .getRawType() + .equals(Provider.class)) { // And a Provider... + return true; + } + } else if (dependency + .getKey() + .getTypeLiteral() + .getRawType() + .equals(Injector.class)) { // If it's the Injector... + return true; + } + return false; + } + + /** + * Returns a key similar to {@code key}, but with an {@literal @}Assisted binding annotation. This + * fails if another binding annotation is clobbered in the process. If the key already has the + * {@literal @}Assisted annotation, it is returned as-is to preserve any String value. + */ + private Key assistKey(Method method, Key key, Errors errors) throws ErrorsException { + if (key.getAnnotationType() == null) { + return key.withAnnotation(DEFAULT_ANNOTATION); + } else if (key.getAnnotationType() == Assisted.class) { + return key; + } else { + errors + .withSource(method) + .addMessage( + "Only @Assisted is allowed for factory parameters, but found @%s", + key.getAnnotationType()); + throw errors.toException(); + } + } + + /** + * At injector-creation time, we initialize the invocation handler. At this time we make sure all + * factory methods will be able to build the target types. + */ + @Inject + @Toolable + void initialize(Injector injector) { + if (this.injector != null) { + throw new ConfigurationException( + ImmutableList.of( + new Message( + FactoryProvider3.class, + "Factories.create() factories may only be used in one Injector!"))); + } + + this.injector = injector; + + for (Map.Entry entry : assistDataByMethod.entrySet()) { + Method method = entry.getKey(); + AssistData data = entry.getValue(); + Object[] args; + if (!data.optimized) { + args = new Object[method.getParameterTypes().length]; + Arrays.fill(args, "dummy object for validating Factories"); + } else { + args = null; // won't be used -- instead will bind to data.providers. + } + getBindingFromNewInjector( + method, args, data); // throws if the binding isn't properly configured + } + } + + /** + * Creates a child injector that binds the args, and returns the binding for the method's result. + */ + public Binding getBindingFromNewInjector( + final Method method, final Object[] args, final AssistData data) { + checkState( + injector != null, + "Factories.create() factories cannot be used until they're initialized by Guice."); + + final Key returnType = data.returnType; + + // We ignore any pre-existing binding annotation. + final Key returnKey = Key.get(returnType.getTypeLiteral(), RETURN_ANNOTATION); + + Module assistedModule = + new AbstractModule() { + @Override + @SuppressWarnings({ + "unchecked", + "rawtypes" + }) // raw keys are necessary for the args array and return value + protected void configure() { + Binder binder = binder().withSource(method); + + int p = 0; + if (!data.optimized) { + for (Key paramKey : data.paramTypes) { + // Wrap in a Provider to cover null, and to prevent Guice from injecting the + // parameter + binder.bind((Key) paramKey).toProvider(Providers.of(args[p++])); + } + } else { + for (Key paramKey : data.paramTypes) { + // Bind to our ThreadLocalProviders. + binder.bind((Key) paramKey).toProvider(data.providers.get(p++)); + } + } + + Constructor constructor = data.constructor; + // Constructor *should* always be non-null here, + // but if it isn't, we'll end up throwing a fairly good error + // message for the user. + if (constructor != null) { + binder + .bind(returnKey) + .toConstructor(constructor, (TypeLiteral) data.implementationType) + .in(Scopes.NO_SCOPE); // make sure we erase any scope on the implementation type + } + } + }; + + Injector forCreate = injector.createChildInjector(assistedModule); + Binding binding = forCreate.getBinding(returnKey); + // If we have providers cached in data, cache the binding for future optimizations. + if (data.optimized) { + data.cachedBinding = binding; + } + return binding; + } + + /** + * When a factory method is invoked, we create a child injector that binds all parameters, then + * use that to get an instance of the return type. + */ + @Override + public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable { + // If we setup a method handle earlier for this method, call it. + // This is necessary for default methods that java8 creates, so we + // can call the default method implementation (and not our proxied version of it). + if (methodHandleByMethod.containsKey(method)) { + return methodHandleByMethod.get(method).invokeWithArguments(args); + } + + if (method.getDeclaringClass().equals(Object.class)) { + if ("equals".equals(method.getName())) { + return proxy == args[0]; + } else if ("hashCode".equals(method.getName())) { + return System.identityHashCode(proxy); + } else { + return method.invoke(this, args); + } + } + + AssistData data = assistDataByMethod.get(method); + checkState(data != null, "No data for method: %s", method); + Provider provider; + if (data.cachedBinding != null) { // Try to get optimized form... + provider = data.cachedBinding.getProvider(); + } else { + provider = getBindingFromNewInjector(method, args, data).getProvider(); + } + try { + int p = 0; + for (ThreadLocalProvider tlp : data.providers) { + tlp.set(args[p++]); + } + return provider.get(); + } catch (ProvisionException e) { + // if this is an exception declared by the factory method, throw it as-is + if (e.getErrorMessages().size() == 1) { + Message onlyError = getOnlyElement(e.getErrorMessages()); + Throwable cause = onlyError.getCause(); + if (cause != null && canRethrow(method, cause)) { + throw cause; + } + } + throw e; + } finally { + for (ThreadLocalProvider tlp : data.providers) { + tlp.remove(); + } + } + } + + @Override + public String toString() { + return factory.getClass().getInterfaces()[0].getName(); + } + + @Override + public int hashCode() { + return Objects.hashCode(factoryKey, collector); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof FactoryProvider3)) { + return false; + } + FactoryProvider3 other = (FactoryProvider3) obj; + return factoryKey.equals(other.factoryKey) && Objects.equal(collector, other.collector); + } + + /** Returns true if {@code thrown} can be thrown by {@code invoked} without wrapping. */ + static boolean canRethrow(Method invoked, Throwable thrown) { + if (thrown instanceof Error || thrown instanceof RuntimeException) { + return true; + } + + for (Class declared : invoked.getExceptionTypes()) { + if (declared.isInstance(thrown)) { + return true; + } + } + + return false; + } + + // not because we'll never know and this is easier than suppressing warnings. + private static class ThreadLocalProvider extends ThreadLocal implements Provider { + @Override + protected Object initialValue() { + throw new IllegalStateException( + "Cannot use optimized @Assisted provider outside the scope of the constructor." + + " (This should never happen. If it does, please report it.)"); + } + } + + /** + * Holder for the appropriate kind of method lookup to use. Due to bugs in Java releases, we have + * to evaluate what approach to take at runtime. We do this by emulating the buggy scenarios: can + * a lookup access private details that it should be able to see? If not, we fail down to using + * full private access. Unfortunately, private access doesn't work in the JDK17+.... but it + * shouldn't be necessary there either, because the buggy lookup checks should be fixed. + */ + private static class SuperMethodSupport { + private static final SuperMethodLookup METHOD_LOOKUP; + + static { + SuperMethodLookup workingLookup = null; + try { + Class hidden = + Class.forName("com.google.inject.assistedinject.internal.LookupTester$Hidden"); + Method method = hidden.getMethod("method"); + Field lookupsField = hidden.getEnclosingClass().getDeclaredField("LOOKUP"); + lookupsField.setAccessible(true); + MethodHandles.Lookup lookups = (MethodHandles.Lookup) lookupsField.get(null); + for (SuperMethodLookup attempt : SuperMethodLookup.values()) { + try { + attempt.superMethodHandle(method, lookups); + workingLookup = attempt; + break; + } catch (ReflectiveOperationException ignored) { + // Keep looping to find a working lookup + } + } + } catch (ReflectiveOperationException ignored) { + // Bail if our internal tests don't exist. + } + // If everything failed, use the worst option. + if (workingLookup == null) { + workingLookup = SuperMethodLookup.PRIVATE_LOOKUP; + } + METHOD_LOOKUP = workingLookup; + } + } + + private static MethodHandle superMethodHandle( + SuperMethodLookup strategy, Method method, Object proxy, MethodHandles.Lookup userLookups) + throws ReflectiveOperationException { + MethodHandles.Lookup lookup = userLookups == null ? MethodHandles.lookup() : userLookups; + MethodHandle handle = strategy.superMethodHandle(method, lookup); + return handle != null ? handle.bindTo(proxy) : null; + } + + private static enum SuperMethodLookup { + UNREFLECT_SPECIAL { + @Override + MethodHandle superMethodHandle(Method method, MethodHandles.Lookup lookup) + throws ReflectiveOperationException { + return lookup.unreflectSpecial(method, method.getDeclaringClass()); + } + }, + FIND_SPECIAL { + @Override + MethodHandle superMethodHandle(Method method, MethodHandles.Lookup lookup) + throws ReflectiveOperationException { + Class declaringClass = method.getDeclaringClass(); + // Before JDK14, unreflectSpecial didn't work in some scenarios. + // So we workaround using findSpecial. See: https://bugs.openjdk.java.net/browse/JDK-8209005 + return lookup.findSpecial( + declaringClass, + method.getName(), + MethodType.methodType(method.getReturnType(), method.getParameterTypes()), + declaringClass); + } + }, + PRIVATE_LOOKUP { + @Override + MethodHandle superMethodHandle(Method method, MethodHandles.Lookup unused) + throws ReflectiveOperationException { + // Even findSpecial fails on JDK8, so we need to manually reflect on private details. + // But note that this will fail 100% of the time on JDK17+, which doesn't allow reflection + // into the JDK internals. + return PrivateLookup.superMethodHandle(method); + } + }; + + abstract MethodHandle superMethodHandle(Method method, MethodHandles.Lookup lookup) + throws ReflectiveOperationException; + }; + + // Note: this isn't a public API, but we need to use it in order to call default methods on (or + // with) non-public types. If it doesn't exist, the code falls back to a less precise check. + static class PrivateLookup { + PrivateLookup() {} + + private static final int ALL_MODES = + Modifier.PRIVATE | Modifier.STATIC /* package */ | Modifier.PUBLIC | Modifier.PROTECTED; + + private static final Constructor privateLookupCxtor = + findPrivateLookupCxtor(); + + private static Constructor findPrivateLookupCxtor() { + try { + Constructor cxtor; + try { + cxtor = MethodHandles.Lookup.class.getDeclaredConstructor(Class.class, int.class); + } catch (NoSuchMethodException ignored) { + cxtor = + MethodHandles.Lookup.class.getDeclaredConstructor( + Class.class, Class.class, int.class); + } + cxtor.setAccessible(true); + return cxtor; + } catch (Exception e) { + // Note: we catch Exception because we want to handle InaccessibleObjectException too, + // but we target JDK8. + // TODO(sameb): When we drop JDK8 support, catch ReflectiveOperation|Security|Inaccessible + return null; + } + } + + static MethodHandle superMethodHandle(Method method) throws ReflectiveOperationException { + if (privateLookupCxtor == null) { + return null; // fall back to assistDataBuilder workaround + } + Class declaringClass = method.getDeclaringClass(); + MethodHandles.Lookup lookup; + if (privateLookupCxtor.getParameterCount() == 2) { + lookup = privateLookupCxtor.newInstance(declaringClass, ALL_MODES); + } else { + lookup = privateLookupCxtor.newInstance(declaringClass, null, ALL_MODES); + } + return lookup.unreflectSpecial(method, declaringClass); + } + } +} diff --git a/common/src/main/java/net/draycia/carbon/common/CarbonChatInternal.java b/common/src/main/java/net/draycia/carbon/common/CarbonChatInternal.java index 9b1f0b9e..82712321 100644 --- a/common/src/main/java/net/draycia/carbon/common/CarbonChatInternal.java +++ b/common/src/main/java/net/draycia/carbon/common/CarbonChatInternal.java @@ -37,6 +37,7 @@ import net.draycia.carbon.common.command.commands.ExecutionCoordinatorHolder; import net.draycia.carbon.common.listeners.Listener; import net.draycia.carbon.common.messages.CarbonMessages; import net.draycia.carbon.common.messaging.MessagingManager; +import net.draycia.carbon.common.messaging.packets.PacketFactory; import net.draycia.carbon.common.users.ProfileCache; import net.draycia.carbon.common.users.ProfileResolver; import net.draycia.carbon.common.users.UserManagerInternal; @@ -138,6 +139,11 @@ public abstract class CarbonChatInternal implements Carb } protected void shutdown() { + this.messagingManager.get().withPacketService(packetService -> { + packetService.queuePacket(this.injector.getInstance(PacketFactory.class).clearLocalPlayersPacket()); + packetService.flushQueue(); // todo remove + }); + // this.messagingManager.get().onShutdown(); // todo fix this taking so long ConcurrentUtil.shutdownExecutor(this.periodicTasks, TimeUnit.MILLISECONDS, 500); this.profileCache.save(); this.profileResolver.shutdown(); diff --git a/common/src/main/java/net/draycia/carbon/common/CarbonCommonModule.java b/common/src/main/java/net/draycia/carbon/common/CarbonCommonModule.java index 7d7459f3..c76c23e4 100644 --- a/common/src/main/java/net/draycia/carbon/common/CarbonCommonModule.java +++ b/common/src/main/java/net/draycia/carbon/common/CarbonCommonModule.java @@ -21,11 +21,16 @@ package net.draycia.carbon.common; import com.google.inject.AbstractModule; import com.google.inject.Injector; +import com.google.inject.Module; +import com.google.inject.Provider; import com.google.inject.Provides; import com.google.inject.Singleton; +import com.google.inject.TypeLiteral; import com.google.inject.assistedinject.FactoryModuleBuilder; +import com.google.inject.assistedinject.FactoryProvider3; import com.google.inject.multibindings.Multibinder; import io.leangen.geantyref.TypeToken; +import java.lang.invoke.MethodHandles; import java.util.Objects; import java.util.UUID; import java.util.concurrent.ScheduledExecutorService; @@ -33,6 +38,7 @@ import net.draycia.carbon.api.channels.ChannelRegistry; import net.draycia.carbon.api.event.CarbonEventHandler; import net.draycia.carbon.common.channels.CarbonChannelRegistry; import net.draycia.carbon.common.command.ArgumentFactory; +import net.draycia.carbon.common.command.argument.PlayerSuggestions; import net.draycia.carbon.common.command.commands.ExecutionCoordinatorHolder; import net.draycia.carbon.common.config.ConfigFactory; import net.draycia.carbon.common.event.CarbonEventHandlerImpl; @@ -58,11 +64,13 @@ import net.draycia.carbon.common.messages.placeholders.UUIDPlaceholderResolver; import net.draycia.carbon.common.messaging.packets.PacketFactory; import net.draycia.carbon.common.users.Backing; import net.draycia.carbon.common.users.CarbonPlayerCommon; +import net.draycia.carbon.common.users.NetworkUsers; import net.draycia.carbon.common.users.UserManagerInternal; import net.draycia.carbon.common.users.db.mysql.MySQLUserManager; import net.draycia.carbon.common.users.db.postgresql.PostgreSQLUserManager; import net.draycia.carbon.common.users.json.JSONUserManager; import net.draycia.carbon.common.util.ConcurrentUtil; +import net.draycia.carbon.common.util.Exceptions; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.key.Key; import net.kyori.adventure.text.Component; @@ -130,9 +138,10 @@ public final class CarbonCommonModule extends AbstractModule { @Override protected void configure() { this.install(new FactoryModuleBuilder().build(ArgumentFactory.class)); - this.install(new FactoryModuleBuilder().build(PacketFactory.class)); + this.install(factoryModule(PacketFactory.class)); this.bind(ChannelRegistry.class).to(CarbonChannelRegistry.class); this.bind(CarbonEventHandler.class).to(CarbonEventHandlerImpl.class); + this.bind(PlayerSuggestions.class).to(NetworkUsers.class); final Multibinder listeners = Multibinder.newSetBinder(this.binder(), Listener.class); listeners.addBinding().to(DeafenHandler.class); @@ -145,4 +154,23 @@ public final class CarbonCommonModule extends AbstractModule { listeners.addBinding().to(RadiusListener.class); } + // Helper to create a FactoryProvider3 module + private static Module factoryModule(final Class factoryInterface) { + return new AbstractModule() { + @Override + protected void configure() { + try { + final Provider factoryProvider = new FactoryProvider3<>( + com.google.inject.Key.get(TypeLiteral.get(factoryInterface)), + null, + MethodHandles.privateLookupIn(factoryInterface, MethodHandles.lookup()) + ); + this.binder().bind(factoryInterface).toProvider(factoryProvider); + } catch (final Exception e) { + throw Exceptions.rethrow(e); + } + } + }; + } + } diff --git a/common/src/main/java/net/draycia/carbon/common/command/commands/ContinueCommand.java b/common/src/main/java/net/draycia/carbon/common/command/commands/ContinueCommand.java index 863bca1d..93290ff0 100644 --- a/common/src/main/java/net/draycia/carbon/common/command/commands/ContinueCommand.java +++ b/common/src/main/java/net/draycia/carbon/common/command/commands/ContinueCommand.java @@ -26,24 +26,16 @@ import cloud.commandframework.minecraft.extras.RichDescription; import com.google.inject.Inject; import java.util.UUID; import net.draycia.carbon.api.CarbonChat; -import net.draycia.carbon.api.event.events.CarbonPrivateChatEvent; import net.draycia.carbon.api.users.CarbonPlayer; -import net.draycia.carbon.api.util.SourcedAudience; import net.draycia.carbon.common.command.CarbonCommand; import net.draycia.carbon.common.command.CommandSettings; import net.draycia.carbon.common.command.Commander; import net.draycia.carbon.common.command.PlayerCommander; -import net.draycia.carbon.common.command.argument.CarbonPlayerArgument; import net.draycia.carbon.common.config.ConfigFactory; -import net.draycia.carbon.common.event.events.CarbonPrivateChatEventImpl; import net.draycia.carbon.common.messages.CarbonMessages; -import net.draycia.carbon.common.util.CloudUtils; import net.kyori.adventure.key.Key; -import net.kyori.adventure.sound.Sound; -import net.kyori.adventure.text.Component; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.NonNull; -import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.framework.qual.DefaultQualifier; @DefaultQualifier(NonNull.class) @@ -53,18 +45,21 @@ public class ContinueCommand extends CarbonCommand { final CommandManager commandManager; final CarbonMessages carbonMessages; final ConfigFactory configFactory; + private final WhisperCommand.WhisperHandler whisper; @Inject public ContinueCommand( final CarbonChat carbonChat, final CommandManager commandManager, final CarbonMessages carbonMessages, - final ConfigFactory configFactory + final ConfigFactory configFactory, + final WhisperCommand.WhisperHandler whisper ) { this.carbonChat = carbonChat; this.commandManager = commandManager; this.carbonMessages = carbonMessages; this.configFactory = configFactory; + this.whisper = whisper; } @Override @@ -104,51 +99,7 @@ public class ContinueCommand extends CarbonCommand { final @MonotonicNonNull CarbonPlayer recipient = this.carbonChat .userManager().user(whisperTarget).join(); - if (sender.equals(recipient)) { - this.carbonMessages.whisperSelfError(sender, CarbonPlayer.renderName(sender)); - return; - } - - if (!recipient.online() || !sender.awareOf(recipient) && !sender.hasPermission("carbon.whisper.vanished")) { - final var rawNameInput = CloudUtils.rawInputByMatchingName(handler.getRawInput(), recipient); - final var exception = new CarbonPlayerArgument.CarbonPlayerParseException(rawNameInput, handler); - - this.carbonMessages.errorCommandArgumentParsing(sender, CloudUtils.message(exception)); - return; - } - - if (sender.ignoring(recipient)) { - this.carbonMessages.whisperIgnoringTarget(sender, CarbonPlayer.renderName(recipient)); - return; - } - - if (recipient.ignoring(sender)) { - this.carbonMessages.whisperTargetIgnoring(sender, CarbonPlayer.renderName(recipient)); - return; - } - - final Component senderName = CarbonPlayer.renderName(sender); - final Component recipientName = CarbonPlayer.renderName(recipient); - - final CarbonPrivateChatEvent privateChatEvent = new CarbonPrivateChatEventImpl(sender, recipient, Component.text(message)); - this.carbonChat.eventHandler().emit(privateChatEvent); - - if (privateChatEvent.cancelled()) { - this.carbonMessages.whisperError(sender, CarbonPlayer.renderName(sender), CarbonPlayer.renderName(recipient)); - return; - } - - this.carbonMessages.whisperSender(new SourcedAudience(sender, sender), senderName, recipientName, privateChatEvent.message()); - this.carbonMessages.whisperRecipient(new SourcedAudience(sender, recipient), senderName, recipientName, privateChatEvent.message()); - this.carbonMessages.whisperConsoleLog(this.carbonChat.server().console(), senderName, recipientName, privateChatEvent.message()); - - final @Nullable Sound messageSound = this.configFactory.primaryConfig().messageSound(); - if (messageSound != null) { - recipient.playSound(messageSound); - } - sender.lastWhisperTarget(recipient.uuid()); - sender.whisperReplyTarget(recipient.uuid()); - recipient.whisperReplyTarget(sender.uuid()); + this.whisper.whisper(sender, recipient, message); }) .build(); diff --git a/common/src/main/java/net/draycia/carbon/common/command/commands/ReplyCommand.java b/common/src/main/java/net/draycia/carbon/common/command/commands/ReplyCommand.java index 6f98ca4b..5a8e5645 100644 --- a/common/src/main/java/net/draycia/carbon/common/command/commands/ReplyCommand.java +++ b/common/src/main/java/net/draycia/carbon/common/command/commands/ReplyCommand.java @@ -26,21 +26,14 @@ import cloud.commandframework.minecraft.extras.RichDescription; import com.google.inject.Inject; import java.util.UUID; import net.draycia.carbon.api.CarbonChat; -import net.draycia.carbon.api.event.events.CarbonPrivateChatEvent; import net.draycia.carbon.api.users.CarbonPlayer; -import net.draycia.carbon.api.util.SourcedAudience; import net.draycia.carbon.common.command.CarbonCommand; import net.draycia.carbon.common.command.CommandSettings; import net.draycia.carbon.common.command.Commander; import net.draycia.carbon.common.command.PlayerCommander; -import net.draycia.carbon.common.command.argument.CarbonPlayerArgument; import net.draycia.carbon.common.config.ConfigFactory; -import net.draycia.carbon.common.event.events.CarbonPrivateChatEventImpl; import net.draycia.carbon.common.messages.CarbonMessages; -import net.draycia.carbon.common.util.CloudUtils; import net.kyori.adventure.key.Key; -import net.kyori.adventure.sound.Sound; -import net.kyori.adventure.text.Component; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; @@ -53,18 +46,21 @@ public class ReplyCommand extends CarbonCommand { final CommandManager commandManager; final CarbonMessages carbonMessages; final ConfigFactory configFactory; + private final WhisperCommand.WhisperHandler whisper; @Inject public ReplyCommand( final CarbonChat carbonChat, final CommandManager commandManager, final CarbonMessages carbonMessages, - final ConfigFactory configFactory + final ConfigFactory configFactory, + final WhisperCommand.WhisperHandler whisper ) { this.carbonChat = carbonChat; this.commandManager = commandManager; this.carbonMessages = carbonMessages; this.configFactory = configFactory; + this.whisper = whisper; } @Override @@ -103,51 +99,7 @@ public class ReplyCommand extends CarbonCommand { final @MonotonicNonNull CarbonPlayer recipient = this.carbonChat.userManager().user(replyTarget).join(); - if (sender.equals(recipient)) { - this.carbonMessages.whisperSelfError(sender, CarbonPlayer.renderName(sender)); - return; - } - - if (!recipient.online() || !sender.awareOf(recipient) && !sender.hasPermission("carbon.whisper.vanished")) { - final var rawNameInput = CloudUtils.rawInputByMatchingName(handler.getRawInput(), recipient); - final var exception = new CarbonPlayerArgument.CarbonPlayerParseException(rawNameInput, handler); - - this.carbonMessages.errorCommandArgumentParsing(sender, CloudUtils.message(exception)); - return; - } - - if (sender.ignoring(recipient)) { - this.carbonMessages.whisperIgnoringTarget(sender, CarbonPlayer.renderName(recipient)); - return; - } - - if (recipient.ignoring(sender)) { - this.carbonMessages.whisperTargetIgnoring(sender, CarbonPlayer.renderName(recipient)); - return; - } - - final Component senderName = CarbonPlayer.renderName(sender); - final Component recipientName = CarbonPlayer.renderName(recipient); - - final CarbonPrivateChatEvent privateChatEvent = new CarbonPrivateChatEventImpl(sender, recipient, Component.text(message)); - this.carbonChat.eventHandler().emit(privateChatEvent); - - if (privateChatEvent.cancelled()) { - this.carbonMessages.whisperError(sender, CarbonPlayer.renderName(sender), CarbonPlayer.renderName(recipient)); - return; - } - - this.carbonMessages.whisperSender(new SourcedAudience(sender, sender), senderName, recipientName, privateChatEvent.message()); - this.carbonMessages.whisperRecipient(new SourcedAudience(sender, recipient), senderName, recipientName, privateChatEvent.message()); - this.carbonMessages.whisperConsoleLog(this.carbonChat.server().console(), senderName, recipientName, privateChatEvent.message()); - - final @Nullable Sound messageSound = this.configFactory.primaryConfig().messageSound(); - if (messageSound != null) { - recipient.playSound(messageSound); - } - sender.lastWhisperTarget(recipient.uuid()); - sender.whisperReplyTarget(recipient.uuid()); - recipient.whisperReplyTarget(sender.uuid()); + this.whisper.whisper(sender, recipient, message); }) .build(); diff --git a/common/src/main/java/net/draycia/carbon/common/command/commands/WhisperCommand.java b/common/src/main/java/net/draycia/carbon/common/command/commands/WhisperCommand.java index f1846eba..82c5abc5 100644 --- a/common/src/main/java/net/draycia/carbon/common/command/commands/WhisperCommand.java +++ b/common/src/main/java/net/draycia/carbon/common/command/commands/WhisperCommand.java @@ -24,23 +24,29 @@ import cloud.commandframework.arguments.standard.StringArgument; import cloud.commandframework.minecraft.extras.MinecraftExtrasMetaKeys; import cloud.commandframework.minecraft.extras.RichDescription; import com.google.inject.Inject; -import net.draycia.carbon.api.CarbonChat; +import com.google.inject.Provider; +import net.draycia.carbon.api.CarbonServer; +import net.draycia.carbon.api.event.CarbonEventHandler; import net.draycia.carbon.api.event.events.CarbonPrivateChatEvent; import net.draycia.carbon.api.users.CarbonPlayer; +import net.draycia.carbon.api.users.UserManager; import net.draycia.carbon.api.util.SourcedAudience; import net.draycia.carbon.common.command.ArgumentFactory; import net.draycia.carbon.common.command.CarbonCommand; import net.draycia.carbon.common.command.CommandSettings; import net.draycia.carbon.common.command.Commander; import net.draycia.carbon.common.command.PlayerCommander; -import net.draycia.carbon.common.command.argument.CarbonPlayerArgument; import net.draycia.carbon.common.config.ConfigFactory; import net.draycia.carbon.common.event.events.CarbonPrivateChatEventImpl; import net.draycia.carbon.common.messages.CarbonMessages; -import net.draycia.carbon.common.util.CloudUtils; +import net.draycia.carbon.common.messaging.MessagingManager; +import net.draycia.carbon.common.messaging.packets.PacketFactory; +import net.draycia.carbon.common.messaging.packets.WhisperPacket; +import net.draycia.carbon.common.users.NetworkUsers; import net.kyori.adventure.key.Key; import net.kyori.adventure.sound.Sound; import net.kyori.adventure.text.Component; +import org.apache.logging.log4j.Logger; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.framework.qual.DefaultQualifier; @@ -48,25 +54,22 @@ import org.checkerframework.framework.qual.DefaultQualifier; @DefaultQualifier(NonNull.class) public class WhisperCommand extends CarbonCommand { - final CarbonChat carbonChat; - final CommandManager commandManager; - final CarbonMessages carbonMessages; + private final CommandManager commandManager; + private final CarbonMessages carbonMessages; private final ArgumentFactory argumentFactory; - final ConfigFactory configFactory; + private final WhisperHandler whisper; @Inject public WhisperCommand( - final CarbonChat carbonChat, final CommandManager commandManager, final CarbonMessages carbonMessages, final ArgumentFactory argumentFactory, - final ConfigFactory configFactory + final WhisperHandler whisper ) { - this.carbonChat = carbonChat; this.commandManager = commandManager; this.carbonMessages = carbonMessages; this.argumentFactory = argumentFactory; - this.configFactory = configFactory; + this.whisper = whisper; } @Override @@ -89,67 +92,147 @@ public class WhisperCommand extends CarbonCommand { .permission("carbon.whisper.message") .senderType(PlayerCommander.class) .meta(MinecraftExtrasMetaKeys.DESCRIPTION, this.carbonMessages.commandWhisperDescription()) - .handler(handler -> { - final CarbonPlayer sender = ((PlayerCommander) handler.getSender()).carbonPlayer(); + .handler(ctx -> { + final CarbonPlayer sender = ((PlayerCommander) ctx.getSender()).carbonPlayer(); if (sender.muted()) { this.carbonMessages.muteCannotSpeak(sender); return; } - final String message = handler.get("message"); - final CarbonPlayer recipient = handler.get("player"); + final String message = ctx.get("message"); + final CarbonPlayer recipient = ctx.get("player"); - if (sender.equals(recipient)) { - this.carbonMessages.whisperSelfError(sender, CarbonPlayer.renderName(sender)); - return; - } - - if (!recipient.online() || !sender.awareOf(recipient) && !sender.hasPermission("carbon.whisper.vanished")) { - final var rawNameInput = CloudUtils.rawInputByMatchingName(handler.getRawInput(), recipient); - final var exception = new CarbonPlayerArgument.CarbonPlayerParseException(rawNameInput, handler); - - this.carbonMessages.errorCommandArgumentParsing(sender, CloudUtils.message(exception)); - return; - } - - if (sender.ignoring(recipient)) { - this.carbonMessages.whisperIgnoringTarget(sender, CarbonPlayer.renderName(recipient)); - return; - } - - if (recipient.ignoring(sender)) { - this.carbonMessages.whisperTargetIgnoring(sender, CarbonPlayer.renderName(recipient)); - return; - } - - final Component senderName = CarbonPlayer.renderName(sender); - final Component recipientName = CarbonPlayer.renderName(recipient); - - final CarbonPrivateChatEvent privateChatEvent = new CarbonPrivateChatEventImpl(sender, recipient, Component.text(message)); - this.carbonChat.eventHandler().emit(privateChatEvent); - - if (privateChatEvent.cancelled()) { - this.carbonMessages.whisperError(sender, CarbonPlayer.renderName(sender), CarbonPlayer.renderName(recipient)); - return; - } - - this.carbonMessages.whisperSender(new SourcedAudience(sender, sender), senderName, recipientName, privateChatEvent.message()); - this.carbonMessages.whisperRecipient(new SourcedAudience(sender, recipient), senderName, recipientName, privateChatEvent.message()); - this.carbonMessages.whisperConsoleLog(this.carbonChat.server().console(), senderName, recipientName, privateChatEvent.message()); - - final @Nullable Sound messageSound = this.configFactory.primaryConfig().messageSound(); - if (messageSound != null) { - recipient.playSound(messageSound); - } - - sender.lastWhisperTarget(recipient.uuid()); - sender.whisperReplyTarget(recipient.uuid()); - recipient.whisperReplyTarget(sender.uuid()); + this.whisper.whisper(sender, recipient, message); }) .build(); this.commandManager.command(command); } + public static final class WhisperHandler { + + private final Logger logger; + private final CarbonMessages carbonMessages; + private final ConfigFactory configFactory; + private final Provider messaging; + private final PacketFactory packetFactory; + private final UserManager userManager; + private final CarbonServer server; + private final CarbonEventHandler events; + private final NetworkUsers network; + + @Inject + private WhisperHandler( + final Logger logger, + final CarbonMessages carbonMessages, + final ConfigFactory configFactory, + final Provider messaging, + final PacketFactory packetFactory, + final UserManager userManager, + final CarbonServer server, + final CarbonEventHandler events, + final NetworkUsers network + ) { + this.logger = logger; + this.carbonMessages = carbonMessages; + this.configFactory = configFactory; + this.messaging = messaging; + this.packetFactory = packetFactory; + this.userManager = userManager; + this.server = server; + this.events = events; + this.network = network; + } + + public void whisper( + final CarbonPlayer sender, + final CarbonPlayer recipient, + final String message + ) { + if (sender.equals(recipient)) { + this.carbonMessages.whisperSelfError(sender, CarbonPlayer.renderName(sender)); + return; + } + + if (!this.network.online(recipient) || !sender.awareOf(recipient) && !sender.hasPermission("carbon.whisper.vanished")) { + //final var rawNameInput = CloudUtils.rawInputByMatchingName(ctx.getRawInput(), recipient); + //final var exception = new CarbonPlayerArgument.CarbonPlayerParseException(/*rawNameInput*/ recipient.username(), null); + + // todo + this.carbonMessages.errorCommandArgumentParsing(sender, Component.text("No such player " + recipient.username())); + return; + } + + final boolean localRecipient = recipient.online(); + + if (sender.ignoring(recipient)) { + this.carbonMessages.whisperIgnoringTarget(sender, CarbonPlayer.renderName(recipient)); + return; + } + + if (recipient.ignoring(sender)) { + this.carbonMessages.whisperTargetIgnoring(sender, CarbonPlayer.renderName(recipient)); + return; + } + + final Component senderName = CarbonPlayer.renderName(sender); + final Component recipientName = CarbonPlayer.renderName(recipient); + + final CarbonPrivateChatEvent privateChatEvent = new CarbonPrivateChatEventImpl(sender, recipient, Component.text(message)); + this.events.emit(privateChatEvent); + + if (privateChatEvent.cancelled()) { + this.carbonMessages.whisperError(sender, CarbonPlayer.renderName(sender), CarbonPlayer.renderName(recipient)); + return; + } + + this.carbonMessages.whisperSender(new SourcedAudience(sender, sender), senderName, recipientName, privateChatEvent.message()); + if (localRecipient) { + this.carbonMessages.whisperRecipient(new SourcedAudience(sender, recipient), senderName, recipientName, privateChatEvent.message()); + } + this.carbonMessages.whisperConsoleLog(this.server.console(), senderName, recipientName, privateChatEvent.message()); + + final @Nullable Sound messageSound = this.configFactory.primaryConfig().messageSound(); + if (localRecipient && messageSound != null) { + recipient.playSound(messageSound); + } + + sender.lastWhisperTarget(recipient.uuid()); + sender.whisperReplyTarget(recipient.uuid()); + if (localRecipient) { + recipient.whisperReplyTarget(sender.uuid()); + } else { + this.messaging.get().withPacketService(packetService -> { + packetService.queuePacket(this.packetFactory.whisperPacket(sender.uuid(), recipient.uuid(), privateChatEvent.message())); + }); + } + } + + public void handlePacket(final WhisperPacket packet) { + final @Nullable CarbonPlayer recipient = this.server.players().stream() + .filter(p -> p.uuid().equals(packet.to())) + .findFirst() + .orElse(null); + if (recipient == null) { + return; + } + this.userManager.user(packet.from()).thenAccept(sender -> { + final Component senderName = CarbonPlayer.renderName(sender); + final Component recipientName = CarbonPlayer.renderName(recipient); + + recipient.whisperReplyTarget(sender.uuid()); + this.carbonMessages.whisperRecipient(new SourcedAudience(sender, recipient), senderName, recipientName, packet.message()); + this.carbonMessages.whisperConsoleLog(this.server.console(), senderName, recipientName, packet.message()); + final @Nullable Sound messageSound = this.configFactory.primaryConfig().messageSound(); + if (messageSound != null) { + recipient.playSound(messageSound); + } + }).exceptionally(ex -> { + this.logger.warn("Failed to handle whisper packet {}", packet, ex); + return null; + }); + } + } + } diff --git a/common/src/main/java/net/draycia/carbon/common/messaging/CarbonChatPacketHandler.java b/common/src/main/java/net/draycia/carbon/common/messaging/CarbonChatPacketHandler.java index 038a7962..eed9a033 100644 --- a/common/src/main/java/net/draycia/carbon/common/messaging/CarbonChatPacketHandler.java +++ b/common/src/main/java/net/draycia/carbon/common/messaging/CarbonChatPacketHandler.java @@ -22,13 +22,21 @@ package net.draycia.carbon.common.messaging; import java.util.ArrayList; import java.util.List; import net.draycia.carbon.api.CarbonChat; +import net.draycia.carbon.api.CarbonServer; +import net.draycia.carbon.api.channels.ChannelRegistry; import net.draycia.carbon.api.channels.ChatChannel; +import net.draycia.carbon.api.event.CarbonEventHandler; import net.draycia.carbon.api.event.events.CarbonChatEvent; import net.draycia.carbon.api.users.CarbonPlayer; import net.draycia.carbon.api.util.KeyedRenderer; +import net.draycia.carbon.common.command.commands.WhisperCommand; import net.draycia.carbon.common.event.events.CarbonChatEventImpl; import net.draycia.carbon.common.messaging.packets.ChatMessagePacket; +import net.draycia.carbon.common.messaging.packets.LocalPlayerChangePacket; +import net.draycia.carbon.common.messaging.packets.LocalPlayersPacket; import net.draycia.carbon.common.messaging.packets.SaveCompletedPacket; +import net.draycia.carbon.common.messaging.packets.WhisperPacket; +import net.draycia.carbon.common.users.NetworkUsers; import net.draycia.carbon.common.users.UserManagerInternal; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.text.Component; @@ -42,17 +50,27 @@ import org.jetbrains.annotations.NotNull; @DefaultQualifier(NonNull.class) public final class CarbonChatPacketHandler extends AbstractMessagingHandler { - private final CarbonChat carbonChat; + private final CarbonEventHandler events; + private final CarbonServer server; + private final ChannelRegistry channels; private final UserManagerInternal userManager; + private final NetworkUsers networkUsers; + private final WhisperCommand.WhisperHandler whisper; CarbonChatPacketHandler( final CarbonChat carbonChat, final MessagingManager messagingManager, - final UserManagerInternal userManager + final UserManagerInternal userManager, + final NetworkUsers networkUsers, + final WhisperCommand.WhisperHandler whisper ) { super(messagingManager.requirePacketService()); - this.carbonChat = carbonChat; + this.events = carbonChat.eventHandler(); + this.server = carbonChat.server(); + this.channels = carbonChat.channelRegistry(); this.userManager = userManager; + this.networkUsers = networkUsers; + this.whisper = whisper; } @Override @@ -60,19 +78,26 @@ public final class CarbonChatPacketHandler extends AbstractMessagingHandler { if (packet instanceof SaveCompletedPacket statePacket) { this.userManager.saveCompleteMessageReceived(statePacket.playerId()); return true; - } - - if (packet instanceof ChatMessagePacket messagePacket) { + } else if (packet instanceof ChatMessagePacket messagePacket) { return this.handleMessagePacket(messagePacket); + } else if (packet instanceof LocalPlayersPacket playersPacket) { + this.networkUsers.handlePacket(playersPacket); + return true; + } else if (packet instanceof LocalPlayerChangePacket playerChangePacket) { + this.networkUsers.handlePacket(playerChangePacket); + return true; + } else if (packet instanceof WhisperPacket whisperPacket) { + this.whisper.handlePacket(whisperPacket); + return true; } return false; } private boolean handleMessagePacket(final ChatMessagePacket messagePacket) { - final CarbonPlayer sender = this.carbonChat.userManager().user(messagePacket.userId()).join(); + final CarbonPlayer sender = this.userManager.user(messagePacket.userId()).join(); - final @Nullable ChatChannel channel = this.carbonChat.channelRegistry().channel(messagePacket.channelKey()); + final @Nullable ChatChannel channel = this.channels.channel(messagePacket.channelKey()); if (channel == null) { return false; @@ -82,7 +107,7 @@ public final class CarbonChatPacketHandler extends AbstractMessagingHandler { final List recipients = channel.recipients(sender); final CarbonChatEvent chatEvent = new CarbonChatEventImpl(sender, messagePacket.message(), recipients, renderers, channel, null, false); - this.carbonChat.eventHandler().emit(chatEvent); + this.events.emit(chatEvent); for (final Audience recipient : recipients) { if (recipient instanceof CarbonPlayer carbonRecipient @@ -99,7 +124,7 @@ public final class CarbonChatPacketHandler extends AbstractMessagingHandler { recipient.sendMessage(renderedMessage); } - this.carbonChat.server().console().sendMessage(Component.text("[Cross-Server] ").append(chatEvent.message())); + this.server.console().sendMessage(Component.text("[Cross-Server] ").append(chatEvent.message())); return true; } diff --git a/common/src/main/java/net/draycia/carbon/common/messaging/MessagingManager.java b/common/src/main/java/net/draycia/carbon/common/messaging/MessagingManager.java index bbec31a7..19905998 100644 --- a/common/src/main/java/net/draycia/carbon/common/messaging/MessagingManager.java +++ b/common/src/main/java/net/draycia/carbon/common/messaging/MessagingManager.java @@ -23,6 +23,9 @@ import com.google.inject.Inject; import com.google.inject.Singleton; import java.io.File; import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.concurrent.ScheduledExecutorService; @@ -30,13 +33,19 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Consumer; import net.draycia.carbon.api.CarbonChat; -import net.draycia.carbon.api.event.events.CarbonShutdownEvent; +import net.draycia.carbon.api.CarbonServer; +import net.draycia.carbon.api.users.CarbonPlayer; import net.draycia.carbon.common.CarbonChatInternal; +import net.draycia.carbon.common.command.commands.WhisperCommand; import net.draycia.carbon.common.config.ConfigFactory; import net.draycia.carbon.common.config.MessagingSettings; -import net.draycia.carbon.common.listeners.PingHandler; import net.draycia.carbon.common.messaging.packets.ChatMessagePacket; +import net.draycia.carbon.common.messaging.packets.LocalPlayerChangePacket; +import net.draycia.carbon.common.messaging.packets.LocalPlayersPacket; +import net.draycia.carbon.common.messaging.packets.PacketFactory; import net.draycia.carbon.common.messaging.packets.SaveCompletedPacket; +import net.draycia.carbon.common.messaging.packets.WhisperPacket; +import net.draycia.carbon.common.users.NetworkUsers; import net.draycia.carbon.common.users.UserManagerInternal; import net.draycia.carbon.common.util.ConcurrentUtil; import net.draycia.carbon.common.util.ExceptionLoggingScheduledThreadPoolExecutor; @@ -70,7 +79,7 @@ public class MessagingManager { private static final byte protocolVersion = 0; private final CarbonChat carbonChat; - private final @MonotonicNonNull ScheduledExecutorService executorService; + private final @MonotonicNonNull ScheduledExecutorService scheduledExecutor; private final @MonotonicNonNull PacketService packetService; private @MonotonicNonNull MessagingService messagingService; @@ -78,9 +87,12 @@ public class MessagingManager { public MessagingManager( final ConfigFactory configFactory, final CarbonChat carbonChat, + final CarbonServer server, final Logger logger, final UserManagerInternal userManager, - final PingHandler pingHandler + final NetworkUsers networkUsers, + final WhisperCommand.WhisperHandler whisper, + final PacketFactory packetFactory ) { if (!configFactory.primaryConfig().messagingSettings().enabled()) { if (!((CarbonChatInternal) carbonChat).isProxy()) { @@ -89,7 +101,7 @@ public class MessagingManager { this.messagingService = EMPTY_MESSAGING_SERVICE; this.packetService = null; this.carbonChat = carbonChat; - this.executorService = null; + this.scheduledExecutor = null; return; } @@ -102,15 +114,24 @@ public class MessagingManager { //PacketManager.register(HeartbeatPacket.class, HeartbeatPacket::new); PacketManager.register(ChatMessagePacket.class, ChatMessagePacket::new); PacketManager.register(SaveCompletedPacket.class, SaveCompletedPacket::new); + PacketManager.register(LocalPlayersPacket.class, LocalPlayersPacket::new); + PacketManager.register(LocalPlayerChangePacket.class, LocalPlayerChangePacket::new); + PacketManager.register(WhisperPacket.class, WhisperPacket::new); - this.packetService = new PacketService(4, false, protocolVersion); - this.executorService = new ExceptionLoggingScheduledThreadPoolExecutor(10, + this.packetService = new PacketService(4, false, protocolVersion) { + // todo super is broken - calls remove on COWIterator + @Override + public boolean removeMessenger(final @NonNull String serviceName) { + return true; + } + }; + this.scheduledExecutor = new ExceptionLoggingScheduledThreadPoolExecutor(4, ConcurrentUtil.carbonThreadFactory(carbonChat.logger(), "MessagingManager"), carbonChat.logger()); this.carbonChat = carbonChat; final MessagingHandlerImpl handlerImpl = new MessagingHandlerImpl(this.packetService); - handlerImpl.addHandler(new CarbonServerHandler(carbonChat.serverId(), this.packetService, handlerImpl)); - handlerImpl.addHandler(new CarbonChatPacketHandler(carbonChat, this, userManager)); + handlerImpl.addHandler(new CarbonServerHandler(server, carbonChat.serverId(), this.packetService, handlerImpl, packetFactory)); + handlerImpl.addHandler(new CarbonChatPacketHandler(carbonChat, this, userManager, networkUsers, whisper)); try { this.initMessagingService(this.packetService, handlerImpl, new File("/"), @@ -126,22 +147,18 @@ public class MessagingManager { this.packetService.flushQueue(); // Broadcast keepalive packets - this.executorService.scheduleAtFixedRate(() -> { + this.scheduledExecutor.scheduleAtFixedRate(() -> { this.packetService.queuePacket(new KeepAlivePacket(carbonChat.serverId())); this.packetService.flushQueue(); }, 5, 5, TimeUnit.SECONDS); - this.executorService.scheduleAtFixedRate(() -> { + this.scheduledExecutor.scheduleAtFixedRate(() -> { try { this.packetService.flushQueue(); } catch (final IndexOutOfBoundsException ignored) { } - }, 0, 1, TimeUnit.SECONDS); - - carbonChat.eventHandler().subscribe(CarbonShutdownEvent.class, 0, false, event -> { - this.onShutdown(); - }); + }, 0, 250, TimeUnit.MILLISECONDS); } public @Nullable PacketService packetService() { @@ -158,14 +175,14 @@ public class MessagingManager { } } - private void onShutdown() { - if (this.executorService != null) { - ConcurrentUtil.shutdownExecutor(this.executorService, TimeUnit.SECONDS, 10); - } + public void onShutdown() { if (this.packetService != null) { this.packetService.flushQueue(); this.packetService.shutdown(); } + if (this.scheduledExecutor != null) { + ConcurrentUtil.shutdownExecutor(this.scheduledExecutor, TimeUnit.MILLISECONDS, 500); + } this.messagingService.close(); } @@ -231,12 +248,30 @@ public class MessagingManager { private static final class CarbonServerHandler extends AbstractServerMessagingHandler { + private final CarbonServer server; + private final PacketFactory packetFactory; + private CarbonServerHandler( - final @NotNull UUID serverId, - final @NotNull PacketService packetService, - final @NotNull MessagingHandler messagingHandler + final @NonNull CarbonServer server, + final @NonNull UUID serverId, + final @NonNull PacketService packetService, + final @NonNull MessagingHandler messagingHandler, + final @NonNull PacketFactory packetFactory ) { super(serverId, packetService, messagingHandler); + this.server = server; + this.packetFactory = packetFactory; + } + + @Override + protected void handleInitialization(final @NonNull InitializationPacket packet) { + super.handleInitialization(packet); + final List players = this.server.players(); + final Map map = new HashMap<>(); + for (final CarbonPlayer player : players) { + map.put(player.uuid(), player.username()); + } + this.packetService.queuePacket(this.packetFactory.localPlayersPacket(map)); } } diff --git a/common/src/main/java/net/draycia/carbon/common/messaging/packets/CarbonPacket.java b/common/src/main/java/net/draycia/carbon/common/messaging/packets/CarbonPacket.java index 36dd392a..fa998cb8 100644 --- a/common/src/main/java/net/draycia/carbon/common/messaging/packets/CarbonPacket.java +++ b/common/src/main/java/net/draycia/carbon/common/messaging/packets/CarbonPacket.java @@ -23,6 +23,8 @@ import io.netty.buffer.ByteBuf; import java.util.HashMap; import java.util.Map; import java.util.UUID; +import java.util.function.BiConsumer; +import java.util.function.Function; import net.kyori.adventure.key.Key; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; @@ -56,21 +58,30 @@ public abstract class CarbonPacket extends AbstractPacket { return Key.key(value); } - protected final void writeStringMap(final Map map, final ByteBuf buffer) { + protected final void writeMap( + final Map map, + final BiConsumer keyWriter, + final BiConsumer valueWriter, + final ByteBuf buffer + ) { this.writeVarInt(map.size(), buffer); - for (final Map.Entry entry : map.entrySet()) { - this.writeString(entry.getKey(), buffer); - this.writeString(entry.getValue(), buffer); + for (final Map.Entry entry : map.entrySet()) { + keyWriter.accept(entry.getKey(), buffer); + valueWriter.accept(entry.getValue(), buffer); } } - protected final Map readStringMap(final ByteBuf buffer) { + protected final Map readMap( + final ByteBuf buffer, + final Function keyReader, + final Function valueReader + ) { final int size = this.readVarInt(buffer); - final Map map = new HashMap<>(); + final Map map = new HashMap<>(); for (int i = 0; i < size; i++) { - map.put(this.readString(buffer), this.readString(buffer)); + map.put(keyReader.apply(buffer), valueReader.apply(buffer)); } return map; diff --git a/common/src/main/java/net/draycia/carbon/common/messaging/packets/LocalPlayerChangePacket.java b/common/src/main/java/net/draycia/carbon/common/messaging/packets/LocalPlayerChangePacket.java new file mode 100644 index 00000000..74ca4e70 --- /dev/null +++ b/common/src/main/java/net/draycia/carbon/common/messaging/packets/LocalPlayerChangePacket.java @@ -0,0 +1,95 @@ +/* + * CarbonChat + * + * Copyright (c) 2023 Josua Parks (Vicarious) + * Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package net.draycia.carbon.common.messaging.packets; + +import com.google.inject.assistedinject.Assisted; +import com.google.inject.assistedinject.AssistedInject; +import io.netty.buffer.ByteBuf; +import java.util.UUID; +import net.draycia.carbon.api.CarbonChat; +import org.checkerframework.checker.nullness.qual.MonotonicNonNull; +import org.checkerframework.checker.nullness.qual.NonNull; +import org.checkerframework.checker.nullness.qual.Nullable; +import org.checkerframework.framework.qual.DefaultQualifier; + +@DefaultQualifier(NonNull.class) +public final class LocalPlayerChangePacket extends CarbonPacket { + + private @MonotonicNonNull UUID playerId; + private @MonotonicNonNull String playerName; + private @MonotonicNonNull ChangeType changeType; + + @AssistedInject + public LocalPlayerChangePacket( + final CarbonChat carbonChat, + final @Assisted UUID playerId, + final @Assisted @Nullable String playerName, + final @Assisted ChangeType changeType + ) { + super(carbonChat.serverId()); + if (changeType == ChangeType.ADD && playerName == null) { + throw new IllegalArgumentException("playerName cannot be null for ChangeType.ADD"); + } + this.playerId = playerId; + this.playerName = playerName; + this.changeType = changeType; + } + + public LocalPlayerChangePacket(final UUID sender, final ByteBuf data) { + super(sender); + this.read(data); + } + + public UUID playerId() { + return this.playerId; + } + + public String playerName() { + return this.playerName; + } + + public ChangeType changeType() { + return this.changeType; + } + + @Override + public void read(final ByteBuf buffer) { + this.playerId = this.readUUID(buffer); + final String type = this.readString(buffer); + this.changeType = ChangeType.valueOf(type); + if (this.changeType == ChangeType.ADD) { + this.playerName = this.readString(buffer); + } + } + + @Override + public void write(final ByteBuf buffer) { + this.writeUUID(this.playerId, buffer); + this.writeString(this.changeType.name(), buffer); + if (this.changeType == ChangeType.ADD) { + this.writeString(this.playerName, buffer); + } + } + + public enum ChangeType { + ADD, REMOVE + } + +} diff --git a/common/src/main/java/net/draycia/carbon/common/messaging/packets/LocalPlayersPacket.java b/common/src/main/java/net/draycia/carbon/common/messaging/packets/LocalPlayersPacket.java new file mode 100644 index 00000000..711fbbb3 --- /dev/null +++ b/common/src/main/java/net/draycia/carbon/common/messaging/packets/LocalPlayersPacket.java @@ -0,0 +1,65 @@ +/* + * CarbonChat + * + * Copyright (c) 2023 Josua Parks (Vicarious) + * Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package net.draycia.carbon.common.messaging.packets; + +import com.google.inject.assistedinject.Assisted; +import com.google.inject.assistedinject.AssistedInject; +import io.netty.buffer.ByteBuf; +import java.util.Map; +import java.util.UUID; +import net.draycia.carbon.api.CarbonChat; +import org.checkerframework.checker.nullness.qual.MonotonicNonNull; +import org.checkerframework.checker.nullness.qual.NonNull; +import org.checkerframework.framework.qual.DefaultQualifier; + +@DefaultQualifier(NonNull.class) +public final class LocalPlayersPacket extends CarbonPacket { + + private @MonotonicNonNull Map players; + + @AssistedInject + public LocalPlayersPacket( + final CarbonChat carbonChat, + final @Assisted Map players + ) { + super(carbonChat.serverId()); + this.players = players; + } + + public LocalPlayersPacket(final UUID sender, final ByteBuf data) { + super(sender); + this.read(data); + } + + public Map players() { + return this.players; + } + + @Override + public void read(final ByteBuf buffer) { + this.players = this.readMap(buffer, this::readUUID, this::readString); + } + + @Override + public void write(final ByteBuf buffer) { + this.writeMap(this.players, this::writeUUID, this::writeString, buffer); + } + +} diff --git a/common/src/main/java/net/draycia/carbon/common/messaging/packets/PacketFactory.java b/common/src/main/java/net/draycia/carbon/common/messaging/packets/PacketFactory.java index abbfa44a..1396ced0 100644 --- a/common/src/main/java/net/draycia/carbon/common/messaging/packets/PacketFactory.java +++ b/common/src/main/java/net/draycia/carbon/common/messaging/packets/PacketFactory.java @@ -19,8 +19,12 @@ */ package net.draycia.carbon.common.messaging.packets; +import com.google.inject.assistedinject.Assisted; +import java.util.Map; import java.util.UUID; +import net.kyori.adventure.text.Component; import org.checkerframework.checker.nullness.qual.NonNull; +import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.framework.qual.DefaultQualifier; @DefaultQualifier(NonNull.class) @@ -28,4 +32,22 @@ public interface PacketFactory { SaveCompletedPacket saveCompletedPacket(UUID playerId); + LocalPlayersPacket localPlayersPacket(Map players); + + default LocalPlayersPacket clearLocalPlayersPacket() { + return this.localPlayersPacket(Map.of()); + } + + LocalPlayerChangePacket localPlayerChangePacket(UUID player, @Nullable String name, LocalPlayerChangePacket.ChangeType type); + + default LocalPlayerChangePacket addLocalPlayerPacket(final UUID id, final String name) { + return this.localPlayerChangePacket(id, name, LocalPlayerChangePacket.ChangeType.ADD); + } + + default LocalPlayerChangePacket removeLocalPlayerPacket(final UUID id) { + return this.localPlayerChangePacket(id, null, LocalPlayerChangePacket.ChangeType.REMOVE); + } + + WhisperPacket whisperPacket(@Assisted("from") UUID from, @Assisted("to") UUID to, Component msg); + } diff --git a/common/src/main/java/net/draycia/carbon/common/messaging/packets/WhisperPacket.java b/common/src/main/java/net/draycia/carbon/common/messaging/packets/WhisperPacket.java new file mode 100644 index 00000000..6a3eb491 --- /dev/null +++ b/common/src/main/java/net/draycia/carbon/common/messaging/packets/WhisperPacket.java @@ -0,0 +1,93 @@ +/* + * CarbonChat + * + * Copyright (c) 2023 Josua Parks (Vicarious) + * Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package net.draycia.carbon.common.messaging.packets; + +import com.google.inject.assistedinject.Assisted; +import com.google.inject.assistedinject.AssistedInject; +import io.netty.buffer.ByteBuf; +import java.util.UUID; +import net.draycia.carbon.api.CarbonChat; +import net.kyori.adventure.text.Component; +import org.checkerframework.checker.nullness.qual.MonotonicNonNull; +import org.checkerframework.checker.nullness.qual.NonNull; +import org.checkerframework.framework.qual.DefaultQualifier; + +@DefaultQualifier(NonNull.class) +public final class WhisperPacket extends CarbonPacket { + + private @MonotonicNonNull UUID from; + private @MonotonicNonNull UUID to; + private @MonotonicNonNull Component message; + + @AssistedInject + public WhisperPacket( + final CarbonChat carbonChat, + final @Assisted("from") UUID from, + final @Assisted("to") UUID to, + final @Assisted Component message + ) { + super(carbonChat.serverId()); + this.from = from; + this.to = to; + this.message = message; + } + + public WhisperPacket(final UUID sender, final ByteBuf data) { + super(sender); + this.read(data); + } + + public UUID from() { + return this.from; + } + + public UUID to() { + return this.to; + } + + public Component message() { + return this.message; + } + + @Override + public void read(final ByteBuf buffer) { + this.from = this.readUUID(buffer); + this.to = this.readUUID(buffer); + this.message = this.readComponent(buffer); + } + + @Override + public void write(final ByteBuf buffer) { + this.writeUUID(this.from, buffer); + this.writeUUID(this.to, buffer); + this.writeComponent(this.message, buffer); + } + + @Override + public String toString() { + return "WhisperPacket{" + + "from=" + this.from + + ", to=" + this.to + + ", message=" + this.message + + ", sender=" + this.sender + + '}'; + } + +} diff --git a/common/src/main/java/net/draycia/carbon/common/users/CachingUserManager.java b/common/src/main/java/net/draycia/carbon/common/users/CachingUserManager.java index 5dc2927e..f3707041 100644 --- a/common/src/main/java/net/draycia/carbon/common/users/CachingUserManager.java +++ b/common/src/main/java/net/draycia/carbon/common/users/CachingUserManager.java @@ -144,6 +144,9 @@ public abstract class CachingUserManager implements UserManagerInternal loggedOut(final UUID uuid) { + this.messagingManager.get().withPacketService(packetService -> { + packetService.queuePacket(this.packetFactory.removeLocalPlayerPacket(uuid)); + }); this.cacheLock.lock(); try { final @Nullable CompletableFuture remove = this.cache.remove(uuid); diff --git a/common/src/main/java/net/draycia/carbon/common/users/NetworkUsers.java b/common/src/main/java/net/draycia/carbon/common/users/NetworkUsers.java new file mode 100644 index 00000000..ab2af647 --- /dev/null +++ b/common/src/main/java/net/draycia/carbon/common/users/NetworkUsers.java @@ -0,0 +1,133 @@ +/* + * CarbonChat + * + * Copyright (c) 2023 Josua Parks (Vicarious) + * Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package net.draycia.carbon.common.users; + +import cloud.commandframework.context.CommandContext; +import com.google.inject.Inject; +import com.google.inject.Singleton; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.stream.Stream; +import net.draycia.carbon.api.CarbonServer; +import net.draycia.carbon.api.users.CarbonPlayer; +import net.draycia.carbon.api.users.UserManager; +import net.draycia.carbon.common.command.Commander; +import net.draycia.carbon.common.command.PlayerCommander; +import net.draycia.carbon.common.command.argument.PlayerSuggestions; +import net.draycia.carbon.common.messaging.packets.LocalPlayerChangePacket; +import net.draycia.carbon.common.messaging.packets.LocalPlayersPacket; +import net.draycia.carbon.common.util.Exceptions; +import org.checkerframework.checker.nullness.qual.NonNull; +import org.checkerframework.framework.qual.DefaultQualifier; + +/** + * Eventually consistent store of who is on each server in the network (besides self). + * + *

Currently used for username suggestions and whispers.

+ */ +@DefaultQualifier(NonNull.class) +@Singleton +public final class NetworkUsers implements PlayerSuggestions { + + private final CarbonServer server; + private final Map> map = new ConcurrentHashMap<>(); + private final UserManager userManager; + + @Inject + private NetworkUsers( + final CarbonServer server, + final UserManager userManager + ) { + this.server = server; + this.userManager = userManager; + } + + public void handlePacket(final LocalPlayerChangePacket packet) { + final Map serverMap = this.map.computeIfAbsent(packet.getSender(), $ -> new ConcurrentHashMap<>()); + + switch (packet.changeType()) { + case ADD -> serverMap.put(packet.playerId(), packet.playerName()); + case REMOVE -> serverMap.remove(packet.playerId()); + } + + this.map.values().removeIf(Map::isEmpty); + } + + public void handlePacket(final LocalPlayersPacket packet) { + if (packet.players().isEmpty()) { + this.map.remove(packet.getSender()); + } else { + final Map serverMap = this.map.computeIfAbsent(packet.getSender(), $ -> new ConcurrentHashMap<>()); + serverMap.clear(); + serverMap.putAll(packet.players()); + } + } + + // PlayerSuggestions impl + @Override + public List apply(final CommandContext ctx, final String input) { + final Commander commander = ctx.getSender(); + + final List local = this.server.players(); + + if (!(commander instanceof PlayerCommander player)) { + return Stream.concat(local.stream().map(CarbonPlayer::username), this.map.values().stream().flatMap(m -> m.values().stream())) + .distinct() + .toList(); + } + final CarbonPlayer carbonPlayer = player.carbonPlayer(); + + final List> remotePlayerFutures = + this.map.values().stream() + .flatMap(m -> m.keySet().stream()) + .map(this.userManager::user) + .toList(); // collect to ensure we request all futures before waiting + final CompletableFuture combinedFuture = CompletableFuture.allOf(remotePlayerFutures.toArray(CompletableFuture[]::new)); + try { + combinedFuture.get(50, TimeUnit.MILLISECONDS); + } catch (final TimeoutException ignore) { + } catch (final Exception e) { + throw Exceptions.rethrow(e); + } + final Stream remote = remotePlayerFutures.stream() + .map(future -> future.getNow(null)) + .filter(Objects::nonNull); + + return Stream.concat(local.stream(), remote) + .filter(carbonPlayer::awareOf) + .map(CarbonPlayer::username) + .distinct() + .toList(); + } + + public boolean online(final CarbonPlayer player) { + if (player.online()) { + return true; + } + return this.map.values().stream().anyMatch(server -> server.containsKey(player.uuid())); + } + +} diff --git a/common/src/main/java/net/draycia/carbon/common/users/ProfileResolver.java b/common/src/main/java/net/draycia/carbon/common/users/ProfileResolver.java index cb60b4c4..bd86ad1c 100644 --- a/common/src/main/java/net/draycia/carbon/common/users/ProfileResolver.java +++ b/common/src/main/java/net/draycia/carbon/common/users/ProfileResolver.java @@ -25,6 +25,7 @@ import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.framework.qual.DefaultQualifier; +// todo use data from NetworkPlayers? @DefaultQualifier(NonNull.class) public interface ProfileResolver { diff --git a/fabric/build.gradle.kts b/fabric/build.gradle.kts index 8ff861d5..0adfc231 100644 --- a/fabric/build.gradle.kts +++ b/fabric/build.gradle.kts @@ -87,6 +87,6 @@ tasks { } modrinth { - gameVersions.set(listOf(libs.versions.fabricMinecraft.get())) + gameVersions.set(listOf(libs.versions.minecraft.get())) loaders.addAll("fabric") } diff --git a/fabric/src/main/java/net/draycia/carbon/fabric/CarbonChatFabricModule.java b/fabric/src/main/java/net/draycia/carbon/fabric/CarbonChatFabricModule.java index cb4244d2..8c560e1a 100644 --- a/fabric/src/main/java/net/draycia/carbon/fabric/CarbonChatFabricModule.java +++ b/fabric/src/main/java/net/draycia/carbon/fabric/CarbonChatFabricModule.java @@ -36,7 +36,6 @@ import net.draycia.carbon.common.CarbonCommonModule; import net.draycia.carbon.common.DataDirectory; import net.draycia.carbon.common.PlatformScheduler; import net.draycia.carbon.common.command.Commander; -import net.draycia.carbon.common.command.argument.PlayerSuggestions; import net.draycia.carbon.common.command.commands.ExecutionCoordinatorHolder; import net.draycia.carbon.common.messages.CarbonMessages; import net.draycia.carbon.common.users.ProfileResolver; @@ -108,13 +107,6 @@ public final class CarbonChatFabricModule extends AbstractModule { return injector.getInstance(FabricMessageRenderer.class); } - @Provides - public PlayerSuggestions playerSuggestions(final MinecraftServerHolder serverHolder) { - return (ctx, input) -> serverHolder.requireServer().getPlayerList().getPlayers().stream() - .map(player -> player.getGameProfile().getName()) - .toList(); - } - @Override public void configure() { this.install(new CarbonCommonModule()); diff --git a/fabric/src/main/java/net/draycia/carbon/fabric/listeners/FabricJoinQuitListener.java b/fabric/src/main/java/net/draycia/carbon/fabric/listeners/FabricJoinQuitListener.java index baef0fab..56978fe4 100644 --- a/fabric/src/main/java/net/draycia/carbon/fabric/listeners/FabricJoinQuitListener.java +++ b/fabric/src/main/java/net/draycia/carbon/fabric/listeners/FabricJoinQuitListener.java @@ -20,8 +20,11 @@ package net.draycia.carbon.fabric.listeners; import com.google.inject.Inject; +import com.google.inject.Provider; import java.util.List; import net.draycia.carbon.common.config.ConfigFactory; +import net.draycia.carbon.common.messaging.MessagingManager; +import net.draycia.carbon.common.messaging.packets.PacketFactory; import net.draycia.carbon.common.users.ProfileCache; import net.draycia.carbon.common.users.UserManagerInternal; import net.fabricmc.fabric.api.networking.v1.PacketSender; @@ -43,23 +46,32 @@ public class FabricJoinQuitListener implements ServerPlayConnectionEvents.Join, private final Logger logger; private final ConfigFactory configFactory; private final UserManagerInternal userManager; + private final Provider messaging; + private final PacketFactory packetFactory; @Inject public FabricJoinQuitListener( final Logger logger, final ConfigFactory configFactory, final ProfileCache profileCache, - final UserManagerInternal userManager + final UserManagerInternal userManager, + final Provider messaging, + final PacketFactory packetFactory ) { this.logger = logger; this.configFactory = configFactory; this.profileCache = profileCache; this.userManager = userManager; + this.messaging = messaging; + this.packetFactory = packetFactory; } @Override public void onPlayReady(final ServerGamePacketListenerImpl handler, final PacketSender sender, final MinecraftServer server) { this.profileCache.cache(handler.getPlayer().getUUID(), handler.getPlayer().getGameProfile().getName()); + this.messaging.get().withPacketService(packetService -> { + packetService.queuePacket(this.packetFactory.addLocalPlayerPacket(handler.getPlayer().getUUID(), handler.getPlayer().getGameProfile().getName())); + }); final @Nullable List suggestions = this.configFactory.primaryConfig().customChatSuggestions(); diff --git a/gradle/libs.versions.yml b/gradle/libs.versions.yml index 7f8a6bae..ecc0e837 100644 --- a/gradle/libs.versions.yml +++ b/gradle/libs.versions.yml @@ -34,7 +34,7 @@ versions: guice: 5.1.0 velocityApi: 3.2.0-SNAPSHOT geantyref: 1.3.11 - fabricMinecraft: 1.20.1 + minecraft: 1.20.1 fabricLoader: 0.14.21 adventurePlatformFabric: 5.9.0 luckPermsApi: 5.3 @@ -306,7 +306,7 @@ dependencies: fabricMinecraft: group: com.mojang name: minecraft - version: { ref: fabricMinecraft } + version: { ref: minecraft } fabricLoader: group: net.fabricmc name: fabric-loader diff --git a/paper/build.gradle.kts b/paper/build.gradle.kts index ad03e6db..491f0712 100644 --- a/paper/build.gradle.kts +++ b/paper/build.gradle.kts @@ -1,3 +1,5 @@ +import xyz.jpenilla.runpaper.task.RunServer + plugins { id("carbon.shadow-platform") id("net.minecrell.plugin-yml.bukkit") @@ -37,7 +39,12 @@ tasks { relocateCloud() } runServer { - minecraftVersion("1.20.1") + version.set(libs.versions.minecraft) + } + register("runServer2") { + version.set(libs.versions.minecraft) + pluginJars.from(shadowJar.flatMap { it.archiveFile }) + runDirectory.set(layout.projectDirectory.dir("run2")) } writeDependencies { } diff --git a/paper/src/main/java/net/draycia/carbon/paper/CarbonChatPaperModule.java b/paper/src/main/java/net/draycia/carbon/paper/CarbonChatPaperModule.java index 49ae1f7d..0b7b9b05 100644 --- a/paper/src/main/java/net/draycia/carbon/paper/CarbonChatPaperModule.java +++ b/paper/src/main/java/net/draycia/carbon/paper/CarbonChatPaperModule.java @@ -21,7 +21,6 @@ package net.draycia.carbon.paper; import cloud.commandframework.CommandManager; import cloud.commandframework.brigadier.CloudBrigadierManager; -import cloud.commandframework.bukkit.parsers.PlayerArgument; import cloud.commandframework.paper.PaperCommandManager; import com.google.inject.AbstractModule; import com.google.inject.Injector; @@ -38,7 +37,6 @@ import net.draycia.carbon.common.CarbonCommonModule; import net.draycia.carbon.common.DataDirectory; import net.draycia.carbon.common.PlatformScheduler; import net.draycia.carbon.common.command.Commander; -import net.draycia.carbon.common.command.argument.PlayerSuggestions; import net.draycia.carbon.common.command.commands.ExecutionCoordinatorHolder; import net.draycia.carbon.common.messages.CarbonMessages; import net.draycia.carbon.common.users.ProfileResolver; @@ -132,7 +130,6 @@ public final class CarbonChatPaperModule extends AbstractModule { this.bind(Logger.class).toInstance(this.logger); this.bind(Path.class).annotatedWith(DataDirectory.class).toInstance(this.bootstrap.getDataFolder().toPath()); this.bind(CarbonServer.class).to(CarbonServerPaper.class); - this.bind(PlayerSuggestions.class).toInstance(new PlayerArgument.PlayerParser()::suggestions); this.bind(ProfileResolver.class).to(PaperProfileResolver.class); this.bind(PlatformScheduler.class).to(PaperScheduler.class); this.bind(new TypeLiteral>() {}).to(PaperUserManager.class); diff --git a/paper/src/main/java/net/draycia/carbon/paper/listeners/PaperPlayerJoinListener.java b/paper/src/main/java/net/draycia/carbon/paper/listeners/PaperPlayerJoinListener.java index 8ecf273b..f6939e3d 100644 --- a/paper/src/main/java/net/draycia/carbon/paper/listeners/PaperPlayerJoinListener.java +++ b/paper/src/main/java/net/draycia/carbon/paper/listeners/PaperPlayerJoinListener.java @@ -20,8 +20,11 @@ package net.draycia.carbon.paper.listeners; import com.google.inject.Inject; +import com.google.inject.Provider; import java.util.List; import net.draycia.carbon.common.config.ConfigFactory; +import net.draycia.carbon.common.messaging.MessagingManager; +import net.draycia.carbon.common.messaging.packets.PacketFactory; import net.draycia.carbon.common.users.ProfileCache; import net.draycia.carbon.paper.PaperUserManager; import org.apache.logging.log4j.Logger; @@ -29,6 +32,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; @@ -44,23 +48,36 @@ public class PaperPlayerJoinListener implements Listener { private final Logger logger; private final ProfileCache profileCache; private final PaperUserManager userManager; + private final Provider messaging; + private final PacketFactory packetFactory; @Inject public PaperPlayerJoinListener( final ConfigFactory configFactory, final Logger logger, final ProfileCache profileCache, - final PaperUserManager userManager + final PaperUserManager userManager, + final Provider messaging, + final PacketFactory packetFactory ) { this.configFactory = configFactory; this.logger = logger; this.profileCache = profileCache; this.userManager = userManager; + this.messaging = messaging; + this.packetFactory = packetFactory; + } + + @EventHandler + public void onLogin(final PlayerLoginEvent event) { + this.profileCache.cache(event.getPlayer().getUniqueId(), event.getPlayer().getName()); } @EventHandler(priority = EventPriority.LOWEST) - public void cacheProfile(final PlayerJoinEvent event) { - this.profileCache.cache(event.getPlayer().getUniqueId(), event.getPlayer().getName()); + public void onJoinEarly(final PlayerJoinEvent event) { + this.messaging.get().withPacketService(packetService -> { + packetService.queuePacket(this.packetFactory.addLocalPlayerPacket(event.getPlayer().getUniqueId(), event.getPlayer().getName())); + }); } @EventHandler(priority = EventPriority.HIGH) diff --git a/velocity/src/main/java/net/draycia/carbon/velocity/CarbonChatVelocityModule.java b/velocity/src/main/java/net/draycia/carbon/velocity/CarbonChatVelocityModule.java index c809ce62..9f1d8007 100644 --- a/velocity/src/main/java/net/draycia/carbon/velocity/CarbonChatVelocityModule.java +++ b/velocity/src/main/java/net/draycia/carbon/velocity/CarbonChatVelocityModule.java @@ -21,7 +21,6 @@ package net.draycia.carbon.velocity; import cloud.commandframework.CommandManager; import cloud.commandframework.velocity.VelocityCommandManager; -import cloud.commandframework.velocity.arguments.PlayerArgument; import com.google.inject.AbstractModule; import com.google.inject.Injector; import com.google.inject.Provides; @@ -39,7 +38,6 @@ import net.draycia.carbon.common.CarbonCommonModule; import net.draycia.carbon.common.DataDirectory; import net.draycia.carbon.common.PlatformScheduler; import net.draycia.carbon.common.command.Commander; -import net.draycia.carbon.common.command.argument.PlayerSuggestions; import net.draycia.carbon.common.command.commands.ExecutionCoordinatorHolder; import net.draycia.carbon.common.messages.CarbonMessages; import net.draycia.carbon.common.users.ProfileResolver; @@ -122,7 +120,6 @@ public final class CarbonChatVelocityModule extends AbstractModule { this.bind(CarbonChat.class).to(CarbonChatVelocity.class); this.bind(CarbonServer.class).to(CarbonServerVelocity.class); - this.bind(PlayerSuggestions.class).toInstance(new PlayerArgument.PlayerParser()::suggestions); this.bind(ProfileResolver.class).to(VelocityProfileResolver.class); this.bind(Path.class).annotatedWith(DataDirectory.class).toInstance(this.dataDirectory); this.bind(Logger.class).toInstance(this.logger);