Search in sources :

Example 1 with Promise

use of services.moleculer.Promise in project moleculer-java by moleculer-java.

the class Cacher method install.

// --- ADD MIDDLEWARE TO ACTION ---
@Override
public Action install(Action action, Tree config) {
    // Is caching enabled?
    Tree cacheNode = config.get("cache");
    if (cacheNode == null) {
        return null;
    }
    // Get cache keys
    Tree keyNode = cacheNode.get("keys");
    final String[] keys;
    if (keyNode == null) {
        keys = null;
    } else {
        List<String> list = keyNode.asList(String.class);
        if (list.isEmpty()) {
            keys = null;
        } else {
            keys = new String[list.size()];
            list.toArray(keys);
        }
    }
    // Get TTL (0 = use default TTL)
    final int ttl = cacheNode.get("ttl", 0);
    return new Action() {

        @Override
        public Object handler(Context ctx) throws Exception {
            String key = getCacheKey(ctx.name, ctx.params, keys);
            return new Promise(resolver -> {
                get(key).then(in -> {
                    if (in == null || in.isNull()) {
                        new Promise(action.handler(ctx)).then(tree -> {
                            set(key, tree, ttl);
                            resolver.resolve(tree);
                        }).catchError(err -> {
                            resolver.reject(err);
                        });
                    } else {
                        resolver.resolve(in);
                    }
                }).catchError(err -> {
                    resolver.reject(err);
                });
            });
        }
    };
}
Also used : Context(services.moleculer.context.Context) List(java.util.List) Action(services.moleculer.service.Action) Middleware(services.moleculer.service.Middleware) Tree(io.datatree.Tree) Context(services.moleculer.context.Context) Name(services.moleculer.service.Name) Promise(services.moleculer.Promise) Promise(services.moleculer.Promise) Action(services.moleculer.service.Action) Tree(io.datatree.Tree)

Example 2 with Promise

use of services.moleculer.Promise in project moleculer-java by moleculer-java.

the class DefaultServiceRegistry method ping.

// --- PING / PONG HANDLING ---
@Override
public Promise ping(long timeoutMillis, String nodeID) {
    // Create new promise
    Promise promise = new Promise();
    // Set timeout
    long timeoutAt;
    if (timeoutMillis > 0) {
        timeoutAt = System.currentTimeMillis() + timeoutMillis;
    } else {
        timeoutAt = 0;
    }
    // Register promise (timeout and response handling)
    String id = uid.nextUID();
    register(id, promise, timeoutAt);
    // Send request via transporter
    Tree message = transporter.createPingPacket(id);
    transporter.publish(Transporter.PACKET_PING, nodeID, message);
    // Return promise
    return promise;
}
Also used : Promise(services.moleculer.Promise) FastBuildTree(services.moleculer.util.FastBuildTree) Tree(io.datatree.Tree)

Example 3 with Promise

use of services.moleculer.Promise in project moleculer-java by moleculer-java.

the class MqttTransporter method subscribed.

@Override
public void subscribed(MqttClient client, Subscription[] requestedSubscriptions, Subscription[] grantedSubscriptions, boolean requestsGranted) {
    for (Subscription s : grantedSubscriptions) {
        String channel = s.getTopic();
        Promise promise = subscriptions.remove(channel);
        if (promise != null) {
            promise.complete();
        }
        if (debug) {
            logger.info("Channel \"" + channel + "\" subscribed successfully.");
        }
    }
}
Also used : Promise(services.moleculer.Promise) Subscription(net.sf.xenqtt.client.Subscription)

Example 4 with Promise

use of services.moleculer.Promise in project moleculer-java by moleculer-java.

the class RedisGetSetClient method disconnect.

// --- DISCONNECT ---
public final Promise disconnect() {
    if (client != null) {
        client.close();
        client = null;
    } else if (clusteredClient != null) {
        clusteredClient.close();
        clusteredClient = null;
    }
    LinkedList<Promise> threads = new LinkedList<>();
    if (group != null) {
        threads.add(new Promise(group.shutdownGracefully(1, 1, TimeUnit.SECONDS)));
    }
    if (resources != null) {
        threads.add(new Promise(resources.shutdown()));
    }
    return Promise.all(threads).then(ok -> {
        if (acceptor != null) {
            acceptor.shutdownNow();
            acceptor = null;
        }
        resources = null;
    });
}
Also used : Promise(services.moleculer.Promise) LinkedList(java.util.LinkedList)

Example 5 with Promise

use of services.moleculer.Promise in project moleculer-java by moleculer-java.

the class CircuitBreakerTest method testRoundRobin.

@Test
public void testRoundRobin() throws Exception {
    // Simple round-robin test
    currentID = 1;
    for (int i = 0; i < 20; i++) {
        Promise p = br.call("test.test", (Tree) null);
        assertTrue(tr.hasMessage(getCurrentID()));
        assertEquals(1, tr.getMessageCount());
        createResponse(true);
        boolean ok = false;
        try {
            p.waitFor();
            ok = true;
        } catch (Exception e) {
        }
        assertTrue(ok);
    }
    // Create fault
    Promise p = br.call("test.test", (Tree) null);
    String nodeID = createResponse(false);
    boolean ok = true;
    try {
        p.waitFor();
    } catch (Exception e) {
        ok = e.toString().contains("unknown error");
    }
    assertFalse(ok);
    ErrorCounter ec = cb.errorCounters.get(new EndpointKey(nodeID, "test.test"));
    assertNotNull(ec);
    assertEquals(1, ec.pointer);
    long now = ec.timestamps[0];
    assertTrue(ec.isAvailable(now));
    // Create faults2
    p = br.call("test.test", (Tree) null);
    nodeID = createResponse(false);
    try {
        p.waitFor();
        ok = true;
    } catch (Exception e) {
        ok = e.toString().contains("unknown error");
    }
    assertFalse(ok);
    ec = cb.errorCounters.get(new EndpointKey(nodeID, "test.test"));
    assertNotNull(ec);
    assertEquals(1, ec.pointer);
    // Create fault
    int node1Count = 0;
    for (int i = 0; i < 30; i++) {
        p = br.call("test.test", (Tree) null);
        nodeID = createResponse(false);
        now = System.currentTimeMillis();
        try {
            p.waitFor();
            ok = true;
        } catch (Exception e) {
            ok = e.toString().contains("unknown error");
        }
        assertFalse(ok);
        if (nodeID.equals("node0")) {
            node1Count++;
            ec = cb.errorCounters.get(new EndpointKey(nodeID, "test.test"));
            assertNotNull(ec);
            if (node1Count < 3) {
                if (node1Count == 1) {
                    assertTrue(ec.timestamps[0] == 0);
                    assertTrue(ec.timestamps[1] > 0);
                    assertTrue(ec.timestamps[2] == 0);
                } else if (node1Count == 2) {
                    assertTrue(ec.timestamps[0] == 0);
                    assertTrue(ec.timestamps[1] > 0);
                    assertTrue(ec.timestamps[2] > 0);
                }
                assertTrue(ec.isAvailable(now));
            } else {
                assertTrue(ec.timestamps[0] > 0);
                assertTrue(ec.timestamps[1] > 0);
                assertTrue(ec.timestamps[2] > 0);
                assertFalse(ec.isAvailable(now));
            }
        }
    }
    // All endpoint is locked
    for (EndpointKey key : cb.errorCounters.keySet()) {
        ec = cb.errorCounters.get(key);
        boolean avail = ec.isAvailable(now);
        assertFalse(avail);
    }
    // Retrying once
    now += 10001;
    assertTrue(ec.isAvailable(now));
    assertFalse(ec.isAvailable(now));
    assertFalse(ec.isAvailable(now));
    // + 5 sec
    now += 5000;
    assertFalse(ec.isAvailable(now));
    assertFalse(ec.isAvailable(now));
    assertFalse(ec.isAvailable(now));
    // + 10 sec (5000 + 5001)
    now += 5001;
    assertTrue(ec.isAvailable(now));
    assertFalse(ec.isAvailable(now));
    assertFalse(ec.isAvailable(now));
}
Also used : Promise(services.moleculer.Promise) Tree(io.datatree.Tree) TimeoutException(java.util.concurrent.TimeoutException) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.Test)

Aggregations

Promise (services.moleculer.Promise)14 Tree (io.datatree.Tree)6 TimeoutException (java.util.concurrent.TimeoutException)5 ExecutionException (java.util.concurrent.ExecutionException)4 LinkedList (java.util.LinkedList)3 Test (org.junit.Test)3 Context (services.moleculer.context.Context)3 HashSet (java.util.HashSet)2 LinkedHashSet (java.util.LinkedHashSet)2 List (java.util.List)2 Objects (java.util.Objects)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 ServiceBroker (services.moleculer.ServiceBroker)2 ServiceBrokerConfig (services.moleculer.config.ServiceBrokerConfig)2 CallOptions (services.moleculer.context.CallOptions)2 ContextFactory (services.moleculer.context.ContextFactory)2 ScanArgs (com.lambdaworks.redis.ScanArgs)1 PrintWriter (java.io.PrintWriter)1 StringWriter (java.io.StringWriter)1 Annotation (java.lang.annotation.Annotation)1