aboutsummaryrefslogtreecommitdiffstats
path: root/messagebus/src/main/java/com/yahoo/messagebus/network/local/LocalNetwork.java
blob: cfe0a35494a27b93746f9d1f9cfbc4a1f6c21ed4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.messagebus.network.local;

import com.yahoo.component.Vtag;
import com.yahoo.jrt.slobrok.api.IMirror;
import com.yahoo.messagebus.EmptyReply;
import com.yahoo.messagebus.Error;
import com.yahoo.messagebus.Message;
import com.yahoo.messagebus.Reply;
import com.yahoo.messagebus.ReplyHandler;
import com.yahoo.messagebus.Routable;
import com.yahoo.messagebus.TraceNode;
import com.yahoo.messagebus.network.Network;
import com.yahoo.messagebus.network.NetworkOwner;
import com.yahoo.messagebus.network.ServiceAddress;
import com.yahoo.messagebus.routing.RoutingNode;
import com.yahoo.text.Utf8String;

import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import static com.yahoo.messagebus.ErrorCode.NO_ADDRESS_FOR_SERVICE;

/**
 * @author Simon Thoresen Hult
 */
public class LocalNetwork implements Network {

    private final Executor executor = Executors.newSingleThreadExecutor();
    private final LocalWire wire;
    private final String hostId;
    private volatile NetworkOwner owner;

    public LocalNetwork() {
        this(new LocalWire());
    }

    public LocalNetwork(LocalWire wire) {
        this.wire = wire;
        this.hostId = wire.newHostId();
    }

    @Override
    public boolean waitUntilReady(double seconds) {
        return true;
    }

    @Override
    public void attach(NetworkOwner owner) {
        this.owner = owner;
    }

    @Override
    public void registerSession(String session) {
        wire.registerService(hostId + "/" + session, this);
    }

    @Override
    public void unregisterSession(String session) {
        wire.unregisterService(hostId + "/" + session);
    }

    @Override
    public boolean allocServiceAddress(RoutingNode recipient) {
        String service = recipient.getRoute().getHop(0).getServiceName();
        ServiceAddress address = wire.resolveServiceAddress(service);
        if (address == null) {
            recipient.setError(new Error(NO_ADDRESS_FOR_SERVICE, "No address for service '" + service + "'."));
            return false;
        }
        recipient.setServiceAddress(address);
        return true;
    }

    @Override
    public void freeServiceAddress(RoutingNode recipient) {
        recipient.setServiceAddress(null);
    }

    @Override
    public void send(Message msg, List<RoutingNode> recipients) {
        for (RoutingNode recipient : recipients) {
            new MessageEnvelope(this, msg, recipient).send();
        }
    }

    private void receiveLater(MessageEnvelope envelope) {
        byte[] payload = envelope.sender.encode(envelope.msg.getProtocol(), envelope.msg);
        executor.execute(new Runnable() {

            @Override
            public void run() {
                Message msg = decode(envelope.msg.getProtocol(), payload, Message.class);
                msg.getTrace().setLevel(envelope.msg.getTrace().getLevel());
                msg.setRoute(envelope.msg.getRoute()).getRoute().removeHop(0);
                msg.setRetryEnabled(envelope.msg.getRetryEnabled());
                msg.setRetry(envelope.msg.getRetry());
                msg.setTimeRemaining(envelope.msg.getTimeRemainingNow());
                msg.pushHandler(reply -> new ReplyEnvelope(LocalNetwork.this, envelope, reply).send());
                owner.deliverMessage(msg, ((LocalServiceAddress) envelope.recipient.getServiceAddress()).getSessionName());
            }
        });
    }

    private void receiveLater(ReplyEnvelope envelope) {
        byte[] payload = envelope.sender.encode(envelope.reply.getProtocol(), envelope.reply);
        executor.execute(() -> {
            Reply reply = decode(envelope.reply.getProtocol(), payload, Reply.class);
            reply.setRetryDelay(envelope.reply.getRetryDelay());
            reply.getTrace().getRoot().addChild(TraceNode.decode(envelope.reply.getTrace().getRoot().encode()));
            for (int i = 0, len = envelope.reply.getNumErrors(); i < len; ++i) {
                Error error = envelope.reply.getError(i);
                reply.addError(new Error(error.getCode(),
                                         error.getMessage(),
                                         error.getService() != null ? error.getService() : envelope.sender.hostId));
            }
            envelope.parent.recipient.handleReply(reply);
        });
    }

    private byte[] encode(Utf8String protocolName, Routable toEncode) {
        if (toEncode.getType() == 0) {
            return new byte[0];
        }
        return owner.getProtocol(protocolName).encode(Vtag.currentVersion, toEncode);
    }

    private <T extends Routable> T decode(Utf8String protocolName, byte[] toDecode, Class<T> clazz) {
        return clazz.cast(toDecode.length == 0 ? new EmptyReply()
                                               : owner.getProtocol(protocolName).decode(Vtag.currentVersion, toDecode));
    }

    @Override
    public void sync() { }

    @Override
    public void shutdown() { }

    @Override
    public String getConnectionSpec() {
        return hostId;
    }

    @Override
    public IMirror getMirror() {
        return wire;
    }

    private static class MessageEnvelope {

        final LocalNetwork sender;
        final Message msg;
        final RoutingNode recipient;

        MessageEnvelope(LocalNetwork sender, Message msg, RoutingNode recipient) {
            this.sender = sender;
            this.msg = msg;
            this.recipient = recipient;
        }

        void send() {
            ((LocalServiceAddress) recipient.getServiceAddress()).getNetwork().receiveLater(this);
        }
    }

    private static class ReplyEnvelope {

        final LocalNetwork sender;
        final MessageEnvelope parent;
        final Reply reply;

        ReplyEnvelope(LocalNetwork sender, MessageEnvelope parent, Reply reply) {
            this.sender = sender;
            this.parent = parent;
            this.reply = reply;
        }

        void send() {
            parent.sender.receiveLater(this);
        }
    }

}