syndicate-java/src/main/java/org/syndicate_lang/actors/Remote.java

86 lines
2.5 KiB
Java
Raw Normal View History

2020-12-04 18:57:47 +00:00
package org.syndicate_lang.actors;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.function.Consumer;
import java.util.function.Function;
public class Remote<T> implements InvocationHandler {
private final Actor _actor;
private final T _target;
public Remote(Actor actor, T target) {
this._actor = actor;
this._target = target;
}
public Actor getActor() {
return _actor;
}
public void async(Consumer<T> f) {
this.async(0, f);
}
public void async(long delayMilliseconds, Consumer<T> f) {
this._actor.later(delayMilliseconds, () -> f.accept(this._target));
}
public Promise<Object> syncVoid(Consumer<T> f) {
return this.syncVoid(0, f);
}
public Promise<Object> syncVoid(long delayMilliseconds, Consumer<T> f) {
return this.sync(delayMilliseconds, (t) -> {
f.accept(t);
return null;
});
}
public<R> Promise<R> sync(Function<T, R> f) {
return this.sync(0, f);
}
public<R> Promise<R> sync(long delayMilliseconds, Function<T, R> f) {
Promise<R> p = new Promise<>();
this._actor.later(
delayMilliseconds,
() -> p.resolveWith(f.apply(this._target)),
() -> p.rejectWith(this._actor.getExitReason()));
return p;
}
@SuppressWarnings("unchecked")
public<I> I proxy(Class<I> c) {
if (!c.isInstance(this._target)) {
throw new IllegalArgumentException("target is not an instance of " + c);
}
return (I) Proxy.newProxyInstance(c.getClassLoader(), new Class[] { c }, this);
}
@SuppressWarnings("unchecked")
public static<I, T extends I> Remote<T> from(I proxy) {
return (Remote<T>) Proxy.getInvocationHandler(proxy);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return this.sync((v) -> {
try {
return method.invoke(v, args);
} catch (IllegalAccessException e) {
throw new ProxyFailure(e);
} catch (InvocationTargetException e) {
throw new ProxyFailure(e.getCause());
}
}).await();
}
@Override
public String toString() {
return super.toString() + "(" + this._actor.getName() + "::" + this._target + ")";
}
}