Updated license
[anna.git] / include / anna / comm / Transport.hpp
1 // ANNA - Anna is Not Nothingness Anymore
2 //
3 // (c) Copyright 2005-2014 Eduardo Ramos Testillano & Francisco Ruiz Rayo
4 //
5 // https://bitbucket.org/testillano/anna
6 //
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
9 // are met:
10 //
11 //     * Redistributions of source code must retain the above copyright
12 // notice, this list of conditions and the following disclaimer.
13 //     * Redistributions in binary form must reproduce the above
14 // copyright notice, this list of conditions and the following disclaimer
15 // in the documentation and/or other materials provided with the
16 // distribution.
17 //     * Neither the name of Google Inc. nor the names of its
18 // contributors may be used to endorse or promote products derived from
19 // this software without specific prior written permission.
20 //
21 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 //
33 // Authors: eduardo.ramos.testillano@gmail.com
34 //          cisco.tierra@gmail.com
35
36
37 #ifndef anna_comm_Transport_hpp
38 #define anna_comm_Transport_hpp
39
40 #include <anna/core/RuntimeException.hpp>
41 #include <anna/core/DataBlock.hpp>
42
43 namespace anna {
44
45 namespace comm {
46
47 class Communicator;
48 class Message;
49
50 /**
51    Clase generica para definir la capa de transporte de cualquier protocolo de comunicaciones.
52
53    Estructura basica que nos permite ordenar el proceso de analizar un mensaje recibido desde
54    cualquier medio. El protocolo conoce los detalles semanticos del mensaje que ha recibido,
55    es decir, conoce como interpretar cada uno de los bytes que componen el mensaje, cuando un
56    mensaje esta completo.
57
58    El principal problema de cualquier protocolo externo a la hora de recibir es conocer cual
59    es el tamao de un determinado mensaje.
60
61    Todos los metodos que se deberian reescribir en las clases heredadas se invocan desde un
62    metodo MT-safe que se encarga de evitar accesos simultaneos desde varios threads, lo cual,
63    evita que tengamos que preocuparnos por establecer secciones criticas en cada uno de los
64    metodos reescritos.
65
66    \warning Los supuestos bajo los que se diseñó éste protocolo facilitan el desarrollo de
67    clases que ofrecen un gran rendimiento, pero imposibilitan el desarrollo del sistema de
68    re-sincronización en caso de que alguno de los mensajes no cumpla los supuestos.
69    Es decir, si nos llega un mensaje errneo nuestro proceso no sera capaz de volver a
70    sincronizarse nunca mas.
71 */
72 class Transport {
73 public:
74   /**
75     Maximum number of bytes kept by each ClientSocket without identifying
76     a message for the own protocol.
77   */
78   WHEN_SINGLETHREAD(
79     static const int DefaultOverQuotaSize = 2048;
80   )
81   WHEN_MULTITHREAD(
82     static const int DefaultOverQuotaSize = 8192;
83   )
84
85   /**
86     Returns true if the transport layer has a timming control system activated.
87   */
88   bool enableTimeout() const throw() { return a_enableTimeout; }
89
90   /**
91     Activates the timming control system for the ClientSocket which were created
92     through this transport layer. They will be automatically closed if no activity
93     is detected in a time interval.
94     \see Communicator::setTimeout.
95   */
96   void activateTimeout() throw() { a_enableTimeout = true; }
97
98   /**
99     Deactivates the timming control system for the ClientSocket which were created
100     through this transport layer.
101   */
102   void deactivateTimeout() throw() { a_enableTimeout = false; }
103
104
105   // Internal use: returns associated input message
106   Message* getInputMessage() throw(RuntimeException) {
107     return (a_inputMessage == NULL) ? nullInputMessage() : a_inputMessage;
108   }
109
110   /**
111     Returns the number of bytes reserved by this protocol for the intermediate buffer.
112     @return number of bytes reserved by this protocol for the intermediate buffer.
113   */
114   int getOverQuotaSize() const throw() { return a_overQuotaSize; }
115
116   /**
117     Establece el numero de bytes que puede mantener este procotolo para cada uno de los
118     ClientSocket sin que se halla identificado el mensaje como propio del protocolo.
119     Si el numero de bytes guardados en la memoria intermedia sobrepasa este numero de
120     bytes se cerrara la conexion con el ClientSocket.
121
122     \param overQuotaSize Numero de maximo de bytes que podemos mantener en la memoria intermedia.
123   */
124   void setOverQuotaSize(const int overQuotaSize) throw() { a_overQuotaSize = (overQuotaSize >= MinOverQuotaSize) ? overQuotaSize : MinOverQuotaSize; }
125
126   /**
127      Debe calcular el tamao previsto del mensaje actual.
128
129      Si se detecta una anomalia irrecuperable en el mensaje debe devolver una excepcion
130      para indicar el error.
131
132      @param dataBlock Bloque con la parte del mensaje disponible hasta el momento.
133
134      @return Si con la informacion disponible no puede establecer la longitud del
135      mensaje devolvera -1 en otro caso devolvera la longitud prevista del mensaje.
136
137      \warning
138         Si el protocolo de transporte implementado detecta problemas al calcular la
139         longitud del mensaje recibido y lanza una excepcion en este metodo el ClientSocket
140         activara los sistemas de recuperacion, si es posible.
141   */
142   virtual int calculeSize(const DataBlock& dataBlock) throw(RuntimeException) = 0;
143
144   /**
145      Debe establecer el modo en que el protocolo va a verificar que el mensaje obtenido
146      coincide con el patrn esperado e interpretar el contenido del mensaje.
147      Este metodo slo se invoca cuando se considera que el mensaje actual esta completo.
148
149      Si se detecta una anomalia irrecuperable en el mensaje debe devolver una excepcion
150      para indicar el error.
151
152      @param message Bloque con lo que hasta el momento se considera el ltimo mensaje recibido
153      por completo.
154
155      \return Un bloque de memoria que contiene el mensaje recibido codificado segn las reglas del
156      protocolo este protocolo de transporte
157   */
158   virtual const Message* decode(const DataBlock& message) throw(RuntimeException) = 0;
159
160   /**
161      Debe establecer la forma en el protocolo va a preparar el envio a la capa de transporte.
162
163      @param message Bloque de datos con la codificacin obtenida mediante cualquiera de los
164      codec disponibles (Ver @ref Codec).
165
166      @return El bloque de memoria con el mensaje que sera enviado a la capa de transporte.
167
168      \warning De no indicarse ninguna otra implementacin devolvera el mensaje tal y como
169      sea recibido.
170   */
171   virtual const DataBlock& code(Message& message) throw(RuntimeException) = 0;
172
173   /**
174      Metodo que inicializa el estado de esta capa de transporte. Sera invocado automaticamente por el
175      nucleo anna.comm.
176   */
177   virtual void clear() throw() { a_forCode.clear(); }
178
179 protected:
180   DataBlock a_forCode; /**< Bloque de memoria usado para guardar el contenido de la codificacion */
181
182   /**
183      Constructor.
184      \param autoSynchronize Indica si el el protocolo instancia permite la sincronizacion automatica.
185      \param overQuotaSize Longitud maxima que puede contener el buffer intermedio antes de cerrar el socket
186       por considerar que no puede sincronizarlo.
187   */
188   Transport() :
189     a_inputMessage(NULL),
190     a_forCode(true),
191     a_enableTimeout(false) {
192     a_overQuotaSize = DefaultOverQuotaSize;
193   }
194
195   /**
196      Establece la instancia del mensaje asociada a este transporte.
197      \param inputMessage Instancia del mensaje a asociar.
198   */
199   void setInputMessage(Message* inputMessage) throw() { a_inputMessage = inputMessage; }
200
201 private:
202   static const int MinOverQuotaSize = 512;
203
204   int a_overQuotaSize;
205   Message* a_inputMessage;
206   bool a_enableTimeout;
207
208   static Message* nullInputMessage() throw(RuntimeException);
209 };
210
211 }
212 }
213
214 #endif