summaryrefslogtreecommitdiff
path: root/comm/MsgStream.cc
blob: f1b5e36bc53648d106ae163d2e48f41aebe9e4fb (plain)
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
/*
 *	Ivy League
 *
 *	Message streams
 *
 *	Copyright 1990-2000
 *	Laboratoire de Recherche en Informatique (LRI)
 *	Centre d'Etudes de la Navigation Aerienne (CENA)
 *
 *	original code by Michel Beaudouin-Lafon,
 *	modified by Stephane Chatty
 *
 *	$Id$
 *
 */

#include "MsgStream.h"
#include "Message.h"
#include "error.h"

/*?class IvlMsgStream
An object of class \typ{IvlMsgStream} is a stream that sends and receives messages:
we call it a message stream.

Messages are sent with the function \fun{Send}.
Output messages are normally buffered to increase performance, but synchronous mode is available.
The output buffer can be flushed by the application, or by the stream itself if needed
(for instance when the buffer is full, or when a synchronous communication is needed).

Incoming messages are handled by the virtual function \fun{HandleRead} of class \typ{IvlChannel}:
it is redefined so that incoming bytes are packed into messages.
When a full message is available, \fun{HandleRead} calls the virtual
function \fun{DecodeMessage} that instantiates a message, then calls the virtual function \fun{Activate} for that
message. Messages are not automatically destroyed.

Messages that need an answer are handled in the following way:
the sender calls the function\fun{Ask}, and is blocked until the answer is received;
any incoming messages are stored for later processing.
When the answer arrives, \fun{Ask} calls the virtual function \fun{DecodeAnswer}.
The returned value of \fun{DecodeAnswer} is then returned by \fun{Ask},
thus returning to the application the reply to its question.

On the receiver's side, the following happens:
when a message sent with \fun{Ask} is received, \fun{DecodeMessage} is called as usual,
but an argument indicates that it is a question that needs an answer.
The receiver must then use \fun{Reply} to send its answer.
Messages can be sent before replying, but it is not possible to send a question
on a message stream that is waiting for an answer:
this would result in a deadlock since the other party is already waiting for an answer
and is buffering other incoming messages.

The default output mode is buffered (i.e. asynchronous).
The buffered output is automatically flushed when a question is sent,
or when the output buffer is full, or explicitly with \fun{Flush}, or with the second argument of \fun{Send}.
The output mode can be switched to a synchronous mode where each message is sent immediately.
% It can also be switched to a locked synchronous mode: this is a synchronous mode where
% the sender waits for each message to be processed before proceeding its execution.
% This is mainly useful for debugging purposes.

\medskip
To use a message stream, a program needs to derive the class \typ{IvlMsgStream}
in order to redefine the virtual functions \fun{DecodeMessage} and \fun{DecodeAnswer}.
\fun{DecodeMessage} treats the incoming message, and will probably call \fun{Send} and \fun{Ask}.
The top level of the program needs just call \fun{HandleRead} in a forever loop.

Most of the time, a program will use several message streams
(for instance to manage several clients).
In this case a channel set is the best way to implement the application:
the definitions in the class \typ{IvlMsgStream} of the functions
\fun{HandleRead}, \fun{HandleWrite} and \fun{HandleSelect} make it easy
to use this class in combination with the class \typ{IvlMultiplexer}.
The virtual function \fun{HandeWrite} of channels is redefined to flush the output buffer.
The virtual function \fun{HandleSelect} of channels is redefined to handle the incoming messages
that were buffered while waiting for an answer.
As for the single stream situation, you need just derive the class \fun{IvlMsgStream} to
redefine the virtual functions \fun{DecodeMessage} and \fun{DecodeAnswer}.
?*/

// ---- no byte swapping ...
// ---- no locked sync mode ...

/*?
These constructors are similar to those of class \typ{IvlSocket}.
?*/
IvlMsgStream :: IvlMsgStream (IvlAddress* bindTo, IvlAddress* connectTo)
: IvlBufStream (bindTo, connectTo),
  Buffered ()
{
	State = WAITING;
	BufferedMessages = false;
	WaitingReply = false;
}

// *** this copy constructor might be automatically generated
/*?nodoc?*/
IvlMsgStream :: IvlMsgStream (const IvlMsgStream& ms)
: IvlBufStream (ms), Buffered (*(IvlMsgBuffer*)&ms.Buffered)
{
      State = ms.State;
      BufferedMessages = ms.BufferedMessages;
      WaitingReply = ms.WaitingReply;
}

/*?nodoc?*/
IvlMsgStream :: ~IvlMsgStream ()
{
	Buffered.Clear ();
}

#if 0
/*?nodoc?*/
IvlChannel*
IvlMsgStream :: Copy () const
{
	return new IvlMsgStream (*this);
}
#endif

// process the input buffer
// waitAnswer indicates whether we are waiting for an answer
// this functions uses a very simple automaton:
//	WAITING:	nothing in the buffer
//	GOT_TYPE:	read the 1 byte header mark of a message
//			MSG / ASK / ANS for messages, questions, answers
//			SYNC / ASYNC / OK for sync management
//	GOT_LENGTH:	read the 4 byte header fo a message
//	DONE:		a full message is in the buffer
//
// WaitingReply is true if a question has been received and Reply has not been called yet
//
/*?hidden?*/
/*!
Return a message when it's been fully read.
!*/
IvlMessage*
IvlMsgStream :: Process (IvlMsgBuffer& buf, bool waitAnswer)
{
	for (;;) {
		switch (State) {
		case WAITING:
			buf.ReadByte (InType);
			if (buf.Error ())
				return 0;
			WaitingReply = false;
			switch (InType) {
			case ASK:
				WaitingReply = true;
			case ANS:
			case MSG:
				State = GOT_TYPE;
				break;
			case SYNC:
			case ASYNC:
			case OK:
			default:
				State = WAITING;
			}
			if (State != GOT_TYPE)
				break;
			// fallthrough
			
		case GOT_TYPE:
			if (! buf.PeekLong ((lword&) InLength))
				return 0;
			buf.NeedSize ((int) InLength - buf.BufLength ());
			State = GOT_LENGTH;
			// fallthrough
			
		case GOT_LENGTH:
			if (buf.BufLength () < InLength)
				return 0;
			State = DONE;
			// fallthrough
		
		case DONE:
			if (waitAnswer) {
				if (InType == ANS) {
					IvlMsgBuffer fake (buf, InLength);
					IvlMessage* ans = DecodeAnswer (fake);
					buf.Flush (InLength);
					State = WAITING;
					return ans;
				} else {
					// store incoming message in a separate buffer
					BufferedMessages = true;
					Buffered.WriteByte (InType);
					Buffered.WriteBuf (buf.Buffer (), InLength);
				}
			} else {
				if (InType == MSG || InType == ASK) {
					// pass a fake buffer to the handler
					IvlMsgBuffer fake (buf, InLength);
					IvlMessage* msg = DecodeMessage (fake);
					if (! msg || !msg->Activate (*this, WaitingReply))
						return 0;
					// *** these returns break the assumption that
					// *** Process empties the buffer.
					// *** this is assumed in HandleRead/HandleSelect
					// *** because BufferedMessages is reset to false;
						
				}
			}
			buf.Flush (InLength);
			State = WAITING;
			// fallthrough
		}
	}
}

/*?nodoc?*/
void
IvlMsgStream :: HandleRead ()
{
	if (BufferedMessages) {
		Process (Buffered, false);
		BufferedMessages = false;
	}
	if (ReadInput () <= 0)
		return;

	Process (InBuffer, false);
}

#if 0
/*?nodoc?*/
bool
IvlMsgStream :: HandleSelect ()
{
	if (BufferedMessages) {
		Process (Buffered, false);
		BufferedMessages = false;
	}
	return false;
}
#endif

/*?
This virtual function is called whenever a complete message is in the buffer.
The buffer contains exactly one message, so that you can use \com{buf.ReadMsg (msg)}
to extract the message from the buffer.
\fun{DecodeMessage} must return the extracted message. The default version returns a dummy \typ{IvlMessage}.
If it returns false, it will be called again with the same arguments next time data arrives on this channel.
The function \typ{MyClient}::\fun{DecodeMessage}
may look like:
\begin{ccode}
IvlMessage*
MyClient :: DecodeMessage (IvlMsgBuffer& buffer)
{
    MyRequest* m = 0;
    lword type;
    buffer.Peek (type, lwsize);
    switch (type) {
    case MyFirstReqType:
        m = new MyFirstRequest;
        break;
    case ...
       ...
    }
    if (m)
        buffer.Get (m);

    return m;
}
\end{ccode}
?*/
IvlMessage*
IvlMsgStream :: DecodeMessage (IvlMsgBuffer&)
{
	return new IvlMessage;
}

/*?
Send a message.
If \var{flush} is true, the output buffer will be flushed.
This also happens when the message stream is in synchronous mode,
or if the output buffer has exceeded its flush size (see \fun{FlushSize}).
?*/
void
IvlMsgStream :: Send (IvlMessage& msg, bool flush)
{
	OutBuffer.WriteByte (MSG);
	WriteMsg (msg);
	if (flush || Sync || OutBuffer.BufLength () >= OutSize)
		Flush ();
}

void
IvlMsgStream :: WriteMsg (IvlMessage& msg)
{
	OutBuffer.WriteMsg (msg);
}

bool
IvlMsgStream :: ReadMsg (IvlMessage& msg)
{
	IvlMsgBuffer& buf = BufferedMessages ? Buffered : InBuffer;
	int l = buf.BufLength (); // store current offset in the buffer
	lword msglen;
	buf >> msglen;
	if (l < msglen)
		return false;
	msg.ReadFrom (*this, msglen);
	/* skip end of msg if necessary */
	int rl = l - buf.BufLength ();
	if (rl == msglen)
		return true;
	else if (rl < msglen) {
		buf.Flush ((int)(msglen) - rl);
		return true;
	} else
		return false;
}

/*?
Send a message and wait for an answer.
Incoming messages that are received while waiting for the answer are kept for later processing.
The answer message is returned by calling the virtual function \fun{DecodeAnswer}.
?*/
IvlMessage*
IvlMsgStream :: Ask (IvlMessage& msg)
{
	if (WaitingReply) {
		::Error (ErrWarn, "IvlMsgStream::Ask", "cannot ask before replying");
		return 0;
	}
	OutBuffer.WriteByte (ASK);
	WriteMsg (msg);
	Flush ();

	IvlMessage* ans = 0;
	do {
		if (ReadInput () <= 0)
			return 0;
		ans = Process (InBuffer, true);
	} while (!ans);
	
	return ans;
}

/*?
This function must be used instead of \fun{Send} to send a reply to a message sent by \fun{Ask}.
?*/
void
IvlMsgStream :: Reply (IvlMessage& msg)
{
	if (! WaitingReply) {
		::Error (ErrWarn, "IvlMsgStream::Reply", "out of phase reply discarded");
		return;
	}
	OutBuffer.WriteByte ((byte) ANS);
	WriteMsg (msg);
	Flush ();
	WaitingReply = false;
}

/*?
This function is called by \fun{Ask} when the answer is in the buffer,
in order to convert it into an object usable by the application.
?*/
IvlMessage*
IvlMsgStream :: DecodeAnswer (IvlMsgBuffer&)
{
	return 0;
}

/*?
Send a buffer containing a message.
If \var{flush} is true, the output buffer will be flushed.
This also happens when the message stream is in synchronous mode,
or if the output IvlMsgBuffer.has exceeded its flush size (see \fun{FlushSize}).
The buffer {\em must} contain a converted message.
This can be used for instance from inside \fun{DecodeMessage} to resend
the incoming message to another client, without having to convert
the buffer to a message.
?*/
void
IvlMsgStream :: Send (IvlMsgBuffer& buf, bool flush)
{
	OutBuffer.WriteByte ((byte) MSG);
	OutBuffer.WriteBuf (buf.Buffer (), buf.BufLength ());
	if (flush || Sync || OutBuffer.BufLength () >= OutSize)
		Flush ();
}