2 @file osrf_app_session.c
3 @brief Implementation of osrfAppSession.
7 #include "opensrf/osrf_app_session.h"
8 #include "opensrf/osrf_stack.h"
10 static char* current_ingress = NULL;
12 struct osrf_app_request_struct {
13 /** The controlling session. */
14 struct osrf_app_session_struct* session;
16 /** Request id. It is the same as the thread_trace of the REQUEST message
17 for which it was created.
20 /** True if we have received a 'request complete' message from our request. */
22 /** The original REQUEST message payload. */
24 /** Linked list of responses to the request. */
27 /** Boolean; if true, then a call that is waiting on a response will reset the
28 timeout and set this variable back to false. */
30 /** Linkage pointers for a linked list. We maintain a hash table of pending requests,
31 and each slot of the hash table is a doubly linked list. */
36 static inline unsigned int request_id_hash( int req_id );
37 static osrfAppRequest* find_app_request( const osrfAppSession* session, int req_id );
38 static void add_app_request( osrfAppSession* session, osrfAppRequest* req );
40 /* Send the given message */
41 static int _osrf_app_session_send( osrfAppSession*, osrfMessage* msg );
43 static int osrfAppSessionMakeLocaleRequest(
44 osrfAppSession* session, const jsonObject* params, const char* method_name,
45 int protocol, osrfStringArray* param_strings, char* locale );
47 /** @brief The global session cache.
49 Key: session_id. Data: osrfAppSession.
51 static osrfHash* osrfAppSessionCache = NULL;
53 // --------------------------------------------------------------------------
55 // --------------------------------------------------------------------------
58 @brief Create a new osrfAppRequest.
59 @param session Pointer to the osrfAppSession that will own the new osrfAppRequest.
60 @param msg Pointer to the osrfMessage representing the request.
61 @return Pointer to the new osrfAppRequest.
63 The calling code is responsible for freeing the osrfAppRequest by calling
64 _osrf_app_request_free().
66 static osrfAppRequest* _osrf_app_request_init(
67 osrfAppSession* session, osrfMessage* msg ) {
69 osrfAppRequest* req = safe_malloc(sizeof(osrfAppRequest));
71 req->session = session;
72 req->request_id = msg->thread_trace;
76 req->reset_timeout = 0;
85 @brief Free an osrfAppRequest and everything it owns.
86 @param req Pointer to an osrfAppRequest.
88 static void _osrf_app_request_free( osrfAppRequest * req ) {
91 osrfMessageFree( req->payload );
93 /* Free the messages in the result queue */
94 osrfMessage* next_msg;
95 while( req->result ) {
96 next_msg = req->result->next;
97 osrfMessageFree( req->result );
98 req->result = next_msg;
106 @brief Append a new message to the list of responses to a request.
107 @param req Pointer to the osrfAppRequest for the original REQUEST message.
108 @param result Pointer to an osrfMessage received in response to the request.
110 For each osrfAppRequest we maintain a linked list of response messages, and traverse
113 static void _osrf_app_request_push_queue( osrfAppRequest* req, osrfMessage* result ){
114 if(req == NULL || result == NULL)
117 osrfLogDebug( OSRF_LOG_MARK, "App Session pushing request [%d] onto request queue",
118 result->thread_trace );
119 if(req->result == NULL) {
120 req->result = result; // Add the first node
124 // Find the last node in the list, and append the new node to it
125 osrfMessage* ptr = req->result;
126 osrfMessage* ptr2 = req->result->next;
136 @brief Remove an osrfAppRequest (identified by request_id) from an osrfAppSession.
137 @param session Pointer to the osrfAppSession that owns the osrfAppRequest.
138 @param req_id request_id of the osrfAppRequest to be removed.
140 void osrf_app_session_request_finish( osrfAppSession* session, int req_id ) {
143 // Search the hash table for the request in question
144 unsigned int index = request_id_hash( req_id );
145 osrfAppRequest* old_req = session->request_hash[ index ];
147 if( old_req->request_id == req_id )
150 old_req = old_req->next;
154 // Remove the request from the doubly linked list
156 old_req->prev->next = old_req->next;
158 session->request_hash[ index ] = old_req->next;
161 old_req->next->prev = old_req->prev;
163 _osrf_app_request_free( old_req );
169 @brief Derive a hash key from a request id.
170 @param req_id The request id.
171 @return The corresponding hash key; an index into request_hash[].
173 If OSRF_REQUEST_HASH_SIZE is a power of two, then this calculation should
174 reduce to a binary AND.
176 static inline unsigned int request_id_hash( int req_id ) {
177 return ((unsigned int) req_id ) % OSRF_REQUEST_HASH_SIZE;
181 @brief Search for an osrfAppRequest in the hash table, given a request id.
182 @param session Pointer to the relevant osrfAppSession.
183 @param req_id The request_id of the osrfAppRequest being sought.
184 @return A pointer to the osrfAppRequest if found, or NULL if not.
186 static osrfAppRequest* find_app_request( const osrfAppSession* session, int req_id ) {
188 osrfAppRequest* req = session->request_hash[ request_id_hash( req_id) ];
190 if( req->request_id == req_id )
200 @brief Add an osrfAppRequest to the hash table of a given osrfAppSession.
201 @param session Pointer to the session to which the request belongs.
202 @param req Pointer to the osrfAppRequest to be stored.
204 Find the right spot in the hash table; then add the request to the linked list at that
205 spot. We just add it to the head of the list, without trying to maintain any particular
208 static void add_app_request( osrfAppSession* session, osrfAppRequest* req ) {
209 if( session && req ) {
210 unsigned int index = request_id_hash( req->request_id );
211 req->next = session->request_hash[ index ];
213 session->request_hash[ index ] = req;
218 @brief Request a reset of the timeout period for a request.
219 @param session Pointer to the relevant osrfAppSession.
220 @param req_id Request ID of the request whose timeout is to be reset.
222 This happens when a client receives a STATUS message with a status code
223 OSRF_STATUS_CONTINUE; in effect the server is asking for more time.
225 The request to be reset is identified by the combination of session and request id.
227 void osrf_app_session_request_reset_timeout( osrfAppSession* session, int req_id ) {
230 osrfLogDebug( OSRF_LOG_MARK, "Resetting request timeout %d", req_id );
231 osrfAppRequest* req = find_app_request( session, req_id );
233 req->reset_timeout = 1;
237 @brief Fetch the next response message to a given previous request, subject to a timeout.
238 @param req Pointer to the osrfAppRequest representing the request.
239 @param timeout Maxmimum time to wait, in seconds.
241 @return Pointer to the next osrfMessage for this request, if one is available, or if it
242 becomes available before the end of the timeout; otherwise NULL;
244 If there is already a message available in the input queue for this request, dequeue and
245 return it immediately. Otherwise wait up to timeout seconds until you either get an
246 input message for the specified request, run out of time, or encounter an error.
248 If the only message we receive for this request is a STATUS message with a status code
249 OSRF_STATUS_COMPLETE, then return NULL. That means that the server has nothing further
250 to send in response to this request.
252 You may also receive other messages for other requests, and other sessions. These other
253 messages will be wholly or partially processed behind the scenes while you wait for the
256 static osrfMessage* _osrf_app_request_recv( osrfAppRequest* req, int timeout ) {
258 if(req == NULL) return NULL;
260 if( req->result != NULL ) {
261 /* Dequeue the next message in the list */
262 osrfMessage* tmp_msg = req->result;
263 req->result = req->result->next;
267 time_t start = time(NULL);
268 time_t remaining = (time_t) timeout;
270 // Wait repeatedly for input messages until you either receive one for the request
271 // you're interested in, run out of time, or encounter an error.
272 // Wait repeatedly because you may also receive messages for other requests, or for
273 // other sessions, and process them behind the scenes. These are not the messages
274 // you're looking for.
275 while( remaining >= 0 ) {
276 /* tell the session to wait for stuff */
277 osrfLogDebug( OSRF_LOG_MARK, "In app_request receive with remaining time [%d]",
281 osrf_app_session_queue_wait( req->session, 0, NULL );
282 if(req->session->transport_error) {
283 osrfLogError(OSRF_LOG_MARK, "Transport error in recv()");
287 if( req->result != NULL ) { /* if we received any results for this request */
288 /* dequeue the first message in the list */
289 osrfLogDebug( OSRF_LOG_MARK, "app_request_recv received a message, returning it" );
290 osrfMessage* ret_msg = req->result;
291 req->result = ret_msg->next;
292 if (ret_msg->sender_locale)
293 osrf_app_session_set_locale(req->session, ret_msg->sender_locale);
301 osrf_app_session_queue_wait( req->session, (int) remaining, NULL );
303 if(req->session->transport_error) {
304 osrfLogError(OSRF_LOG_MARK, "Transport error in recv()");
308 if( req->result != NULL ) { /* if we received any results for this request */
309 /* dequeue the first message in the list */
310 osrfLogDebug( OSRF_LOG_MARK, "app_request_recv received a message, returning it");
311 osrfMessage* ret_msg = req->result;
312 req->result = ret_msg->next;
313 if (ret_msg->sender_locale)
314 osrf_app_session_set_locale(req->session, ret_msg->sender_locale);
322 // Determine how much time is left
323 if(req->reset_timeout) {
324 // We got a reprieve. This happens when a client receives a STATUS message
325 // with a status code OSRF_STATUS_CONTINUE. We restart the timer from the
326 // beginning -- but only once. We reset reset_timeout to zero. so that a
327 // second attempted reprieve will allow, at most, only one more second.
328 remaining = (time_t) timeout;
329 req->reset_timeout = 0;
330 osrfLogDebug( OSRF_LOG_MARK, "Received a timeout reset");
332 remaining -= (int) (time(NULL) - start);
336 // Timeout exhausted; no messages for the request in question
337 char* paramString = jsonObjectToJSON(req->payload->_params);
338 osrfLogInfo( OSRF_LOG_MARK, "Returning NULL from app_request_recv after timeout: %s %s",
339 req->payload->method_name, paramString);
345 // --------------------------------------------------------------------------
347 // --------------------------------------------------------------------------
350 @brief Install a copy of a locale string in a specified session.
351 @param session Pointer to the osrfAppSession in which the locale is to be installed.
352 @param locale The locale string to be copied and installed.
353 @return A pointer to the installed copy of the locale string.
355 char* osrf_app_session_set_locale( osrfAppSession* session, const char* locale ) {
356 if (!session || !locale)
359 if(session->session_locale) {
360 if( strlen(session->session_locale) >= strlen(locale) ) {
361 /* There's room available; just copy */
362 strcpy(session->session_locale, locale);
364 free(session->session_locale);
365 session->session_locale = strdup( locale );
368 session->session_locale = strdup( locale );
371 return session->session_locale;
375 @brief Install a copy of a ingress string as the new default.
376 @param session Pointer to the new strdup'ed default_ingress
377 @param ingress The ingress string to be copied and installed.
379 char* osrfAppSessionSetIngress(const char* ingress) {
380 if (!ingress) return NULL;
382 free(current_ingress);
383 return current_ingress = strdup(ingress);
387 @brief Returns the current ingress value
388 @return A pointer to the installed copy of the ingress string
390 const char* osrfAppSessionGetIngress() {
391 return current_ingress;
395 @brief Find the osrfAppSession for a given session id.
396 @param session_id The session id to look for.
397 @return Pointer to the corresponding osrfAppSession if found, or NULL if not.
399 Search the global session cache for the specified session id.
401 osrfAppSession* osrf_app_session_find_session( const char* session_id ) {
403 return osrfHashGet( osrfAppSessionCache, session_id );
409 @brief Add a session to the global session cache, keyed by session id.
410 @param session Pointer to the osrfAppSession to be added.
412 If a cache doesn't exist yet, create one. It's an osrfHash using session ids for the
413 key and osrfAppSessions for the data.
415 static void _osrf_app_session_push_session( osrfAppSession* session ) {
417 if( osrfAppSessionCache == NULL )
418 osrfAppSessionCache = osrfNewHash();
419 if( osrfHashGet( osrfAppSessionCache, session->session_id ) )
420 return; // A session with this id is already in the cache. Shouldn't happen.
421 osrfHashSet( osrfAppSessionCache, session, session->session_id );
426 @brief Create an osrfAppSession for a client.
427 @param remote_service Name of the service to which to connect
428 @return Pointer to the new osrfAppSession if successful, or NULL upon error.
430 Allocate memory for an osrfAppSession, and initialize it as follows:
432 - For talking with Jabber, grab an existing transport_client. It must have been
433 already set up by a prior call to osrfSystemBootstrapClientResc().
434 - Build a Jabber ID for addressing the service.
435 - Build a session ID based on a fine-grained timestamp and a process ID. This ID is
436 intended to be unique across the system, but uniqueness is not strictly guaranteed.
437 - Initialize various other bits and scraps.
438 - Add the session to the global session cache.
440 Do @em not connect to the service at this point.
442 osrfAppSession* osrfAppSessionClientInit( const char* remote_service ) {
444 if (!remote_service) {
445 osrfLogWarning( OSRF_LOG_MARK, "No remote service specified in osrfAppSessionClientInit");
449 osrfAppSession* session = safe_malloc(sizeof(osrfAppSession));
451 // Grab an existing transport_client for talking with Jabber
452 session->transport_handle = osrfSystemGetTransportClient();
453 if( session->transport_handle == NULL ) {
454 osrfLogWarning( OSRF_LOG_MARK, "No transport client for service 'client'");
459 // Get a list of domain names from the config settings;
460 // ignore all but the first one in the list.
461 osrfStringArray* arr = osrfNewStringArray(8);
462 osrfConfigGetValueList(NULL, arr, "/domain");
463 const char* domain = osrfStringArrayGetString(arr, 0);
465 osrfLogWarning( OSRF_LOG_MARK, "No domains specified in the OpenSRF config file");
467 osrfStringArrayFree(arr);
471 // Get a router name from the config settings.
472 char* router_name = osrfConfigGetValue(NULL, "/router_name");
474 osrfLogWarning( OSRF_LOG_MARK, "No router name specified in the OpenSRF config file");
476 osrfStringArrayFree(arr);
480 char target_buf[512];
481 target_buf[ 0 ] = '\0';
483 // Using the router name, domain, and service name,
484 // build a Jabber ID for addressing the service.
485 int len = snprintf( target_buf, sizeof(target_buf), "%s@%s/%s",
486 router_name ? router_name : "(null)",
487 domain ? domain : "(null)",
488 remote_service ? remote_service : "(null)" );
489 osrfStringArrayFree(arr);
492 if( len >= sizeof( target_buf ) ) {
493 osrfLogWarning( OSRF_LOG_MARK, "Buffer overflow for remote_id");
498 session->remote_id = strdup(target_buf);
499 session->orig_remote_id = strdup(session->remote_id);
500 session->remote_service = strdup(remote_service);
501 session->session_locale = NULL;
502 session->transport_error = 0;
504 session->outbuf = NULL; // Not used by client
506 #ifdef ASSUME_STATELESS
507 session->stateless = 1;
508 osrfLogDebug( OSRF_LOG_MARK, "%s session is stateless", remote_service );
510 session->stateless = 0;
511 osrfLogDebug( OSRF_LOG_MARK, "%s session is NOT stateless", remote_service );
514 /* build a chunky, random session id */
517 snprintf(id, sizeof(id), "%f.%d%ld", get_timestamp_millis(), (int)time(NULL), (long) getpid());
518 session->session_id = strdup(id);
519 osrfLogDebug( OSRF_LOG_MARK, "Building a new client session with id [%s] [%s]",
520 session->remote_service, session->session_id );
522 session->thread_trace = 0;
523 session->state = OSRF_SESSION_DISCONNECTED;
524 session->type = OSRF_SESSION_CLIENT;
526 session->userData = NULL;
527 session->userDataFree = NULL;
529 // Initialize the hash table
531 for( i = 0; i < OSRF_REQUEST_HASH_SIZE; ++i )
532 session->request_hash[ i ] = NULL;
534 _osrf_app_session_push_session( session );
539 @brief Create an osrfAppSession for a server.
540 @param session_id The session ID. In practice this comes from the thread member of
541 the transport message from the client.
542 @param our_app The name of the service being provided.
543 @param remote_id Jabber ID of the client.
544 @return Pointer to the newly created osrfAppSession if successful, or NULL upon failure.
546 If there is already a session with the specified id, report an error. Otherwise:
548 - Allocate memory for an osrfAppSession.
549 - For talking with Jabber, grab an existing transport_client. It should have been
550 already set up by a prior call to osrfSystemBootstrapClientResc().
551 - Install a copy of the @a our_app string as remote_service.
552 - Install copies of the @a remote_id string as remote_id and orig_remote_id.
553 - Initialize various other bits and scraps.
554 - Add the session to the global session cache.
556 Do @em not respond to the client at this point.
558 osrfAppSession* osrf_app_server_session_init(
559 const char* session_id, const char* our_app, const char* remote_id ) {
561 osrfLogDebug( OSRF_LOG_MARK, "Initing server session with session id %s, service %s,"
562 " and remote_id %s", session_id, our_app, remote_id );
564 osrfAppSession* session = osrf_app_session_find_session( session_id );
566 osrfLogWarning( OSRF_LOG_MARK, "App session already exists for session id %s",
571 session = safe_malloc(sizeof(osrfAppSession));
573 // Grab an existing transport_client for talking with Jabber
574 session->transport_handle = osrfSystemGetTransportClient();
575 if( session->transport_handle == NULL ) {
576 osrfLogWarning( OSRF_LOG_MARK, "No transport client for service '%s'", our_app );
581 // Decide from a config setting whether the session is stateless or not. However
582 // this determination is pointless because it will immediately be overruled according
583 // to the compile-time macro ASSUME_STATELESS.
585 char* statel = osrf_settings_host_value("/apps/%s/stateless", our_app );
587 stateless = atoi( statel );
590 session->remote_id = strdup(remote_id);
591 session->orig_remote_id = strdup(remote_id);
592 session->session_id = strdup(session_id);
593 session->remote_service = strdup(our_app);
594 session->stateless = stateless;
596 #ifdef ASSUME_STATELESS
597 session->stateless = 1;
599 session->stateless = 0;
602 session->thread_trace = 0;
603 session->state = OSRF_SESSION_DISCONNECTED;
604 session->type = OSRF_SESSION_SERVER;
605 session->session_locale = NULL;
607 session->userData = NULL;
608 session->userDataFree = NULL;
609 session->transport_error = 0;
611 // Initialize the hash table
613 for( i = 0; i < OSRF_REQUEST_HASH_SIZE; ++i )
614 session->request_hash[ i ] = NULL;
617 session->outbuf = buffer_init( 4096 );
619 _osrf_app_session_push_session( session );
624 @brief Create a REQUEST message, send it, and save it for future reference.
625 @param session Pointer to the current session, which has the addressing information.
626 @param params One way of specifying the parameters for the method.
627 @param method_name The name of the method to be called.
628 @param protocol Protocol.
629 @param param_strings Another way of specifying the parameters for the method.
630 @return The request ID of the resulting REQUEST message, or -1 upon error.
632 DEPRECATED. Use osrfAppSessionSendRequest() instead. It is identical except that it
633 doesn't use the param_strings argument, which is redundant, confusing, and unused.
635 If @a params is non-NULL, use it to specify the parameters to the method. Otherwise
636 use @a param_strings.
638 If @a params points to a JSON_ARRAY, then pass each element of the array as a separate
639 parameter. If @a params points to any other kind of jsonObject, pass it as a single
642 If @a params is NULL, and @a param_strings is not NULL, then each pointer in the
643 osrfStringArray must point to a JSON string encoding a parameter. Pass them.
645 At this writing, all calls to this function use @a params to pass parameters, rather than
648 This function is a thin wrapper for osrfAppSessionMakeLocaleRequest().
650 int osrfAppSessionMakeRequest(
651 osrfAppSession* session, const jsonObject* params,
652 const char* method_name, int protocol, osrfStringArray* param_strings ) {
654 osrfLogWarning( OSRF_LOG_MARK, "Function osrfAppSessionMakeRequest() is deprecated; "
655 "call osrfAppSessionSendRequest() instead" );
656 return osrfAppSessionMakeLocaleRequest( session, params,
657 method_name, protocol, param_strings, NULL );
661 @brief Create a REQUEST message, send it, and save it for future reference.
662 @param session Pointer to the current session, which has the addressing information.
663 @param params One way of specifying the parameters for the method.
664 @param method_name The name of the method to be called.
665 @param protocol Protocol.
666 @return The request ID of the resulting REQUEST message, or -1 upon error.
668 If @a params points to a JSON_ARRAY, then pass each element of the array as a separate
669 parameter. If @a params points to any other kind of jsonObject, pass it as a single
672 This function is a thin wrapper for osrfAppSessionMakeLocaleRequest().
674 int osrfAppSessionSendRequest( osrfAppSession* session, const jsonObject* params,
675 const char* method_name, int protocol ) {
677 return osrfAppSessionMakeLocaleRequest( session, params,
678 method_name, protocol, NULL, NULL );
682 @brief Create a REQUEST message, send it, and save it for future reference.
683 @param session Pointer to the current session, which has the addressing information.
684 @param params One way of specifying the parameters for the method.
685 @param method_name The name of the method to be called.
686 @param protocol Protocol.
687 @param param_strings Another way of specifying the parameters for the method.
688 @param locale Pointer to a locale string.
689 @return The request ID of the resulting REQUEST message, or -1 upon error.
691 See the discussion of osrfAppSessionSendRequest(), which at this writing is the only
692 place that calls this function, except for the similar but deprecated function
693 osrfAppSessionMakeRequest().
695 At this writing, the @a param_strings and @a locale parameters are always NULL.
697 static int osrfAppSessionMakeLocaleRequest(
698 osrfAppSession* session, const jsonObject* params, const char* method_name,
699 int protocol, osrfStringArray* param_strings, char* locale ) {
701 if(session == NULL) return -1;
705 osrfMessage* req_msg = osrf_message_init( REQUEST, ++(session->thread_trace), protocol );
706 osrf_message_set_method(req_msg, method_name);
709 osrf_message_set_locale(req_msg, locale);
710 } else if (session->session_locale) {
711 osrf_message_set_locale(req_msg, session->session_locale);
714 if (!current_ingress)
715 osrfAppSessionSetIngress("opensrf");
716 osrfMessageSetIngress(req_msg, current_ingress);
719 osrf_message_set_params(req_msg, params);
725 for(i = 0; i!= param_strings->size ; i++ ) {
726 osrf_message_add_param(req_msg,
727 osrfStringArrayGetString(param_strings,i));
732 osrfAppRequest* req = _osrf_app_request_init( session, req_msg );
733 if(_osrf_app_session_send( session, req_msg ) ) {
734 osrfLogWarning( OSRF_LOG_MARK, "Error sending request message [%d]",
735 session->thread_trace );
736 _osrf_app_request_free(req);
740 osrfLogDebug( OSRF_LOG_MARK, "Pushing [%d] onto request queue for session [%s] [%s]",
741 req->request_id, session->remote_service, session->session_id );
742 add_app_request( session, req );
743 return req->request_id;
747 @brief Mark an osrfAppRequest (identified by session and ID) as complete.
748 @param session Pointer to the osrfAppSession that owns the request.
749 @param request_id Request ID of the osrfAppRequest.
751 void osrf_app_session_set_complete( osrfAppSession* session, int request_id ) {
755 osrfAppRequest* req = find_app_request( session, request_id );
761 @brief Determine whether a osrfAppRequest, identified by session and ID, is complete.
762 @param session Pointer to the osrfAppSession that owns the request.
763 @param request_id Request ID of the osrfAppRequest.
764 @return Non-zero if the request is complete; zero if it isn't, or if it can't be found.
766 int osrf_app_session_request_complete( const osrfAppSession* session, int request_id ) {
770 osrfAppRequest* req = find_app_request( session, request_id );
772 return req->complete;
778 @brief Reset the remote ID of a session to its original remote ID.
779 @param session Pointer to the osrfAppSession to be reset.
781 void osrf_app_session_reset_remote( osrfAppSession* session ){
785 osrfLogDebug( OSRF_LOG_MARK, "App Session [%s] [%s] resetting remote id to %s",
786 session->remote_service, session->session_id, session->orig_remote_id );
788 osrf_app_session_set_remote( session, session->orig_remote_id );
792 @brief Set a session's remote ID to a specified value.
793 @param session Pointer to the osrfAppSession whose remote ID is to be set.
794 @param remote_id Pointer to the new remote id.
796 void osrf_app_session_set_remote( osrfAppSession* session, const char* remote_id ) {
797 if( session == NULL || remote_id == NULL )
800 if( session->remote_id ) {
801 if( strlen(session->remote_id) >= strlen(remote_id) ) {
802 // There's enough room; just copy it
803 strcpy(session->remote_id, remote_id);
805 free(session->remote_id );
806 session->remote_id = strdup( remote_id );
809 session->remote_id = strdup( remote_id );
813 @brief Append an osrfMessage to the list of responses to an osrfAppRequest.
814 @param session Pointer to the osrfAppSession that owns the request.
815 @param msg Pointer to the osrfMessage to be added.
817 The thread_trace member of the osrfMessage is the request_id of the osrfAppRequest.
818 Find the corresponding request in the session and append the osrfMessage to its list.
820 void osrf_app_session_push_queue( osrfAppSession* session, osrfMessage* msg ) {
821 if( session && msg ) {
822 osrfAppRequest* req = find_app_request( session, msg->thread_trace );
824 _osrf_app_request_push_queue( req, msg );
829 @brief Connect to the remote service.
830 @param session Pointer to the osrfAppSession for the service.
831 @return 1 if successful, or 0 if not.
833 If already connected, exit immediately, reporting success. Otherwise, build a CONNECT
834 message and send it to the service. Wait for up to five seconds for an acknowledgement.
836 The timeout value is currently hard-coded. Perhaps it should be configurable.
838 int osrfAppSessionConnect( osrfAppSession* session ) {
843 if(session->state == OSRF_SESSION_CONNECTED) {
847 int timeout = 5; /* XXX CONFIG VALUE */
849 osrfLogDebug( OSRF_LOG_MARK, "AppSession connecting to %s", session->remote_id );
851 /* defaulting to protocol 1 for now */
852 osrfMessage* con_msg = osrf_message_init( CONNECT, session->thread_trace, 1 );
854 // Address this message to the router
855 osrf_app_session_reset_remote( session );
856 session->state = OSRF_SESSION_CONNECTING;
857 int ret = _osrf_app_session_send( session, con_msg );
858 osrfMessageFree(con_msg);
862 time_t start = time(NULL);
863 time_t remaining = (time_t) timeout;
865 // Wait for the acknowledgement. We look for it repeatedly because, under the covers,
866 // we may receive and process messages other than the one we're looking for.
867 while( session->state != OSRF_SESSION_CONNECTED && remaining >= 0 ) {
868 osrf_app_session_queue_wait( session, remaining, NULL );
869 if(session->transport_error) {
870 osrfLogError(OSRF_LOG_MARK, "cannot communicate with %s", session->remote_service);
873 remaining -= (int) (time(NULL) - start);
876 if(session->state == OSRF_SESSION_CONNECTED)
877 osrfLogDebug( OSRF_LOG_MARK, " * Connected Successfully to %s", session->remote_service );
879 if(session->state != OSRF_SESSION_CONNECTED)
886 @brief Disconnect from the remote service. No response is expected.
887 @param session Pointer to the osrfAppSession to be disconnected.
888 @return 1 in all cases.
890 If we're already disconnected, return immediately without doing anything. Likewise if
891 we have a stateless session and we're in the process of connecting. Otherwise, send a
892 DISCONNECT message to the service.
894 int osrf_app_session_disconnect( osrfAppSession* session){
898 if(session->state == OSRF_SESSION_DISCONNECTED)
901 if(session->stateless && session->state != OSRF_SESSION_CONNECTED) {
902 osrfLogDebug( OSRF_LOG_MARK,
903 "Exiting disconnect on stateless session %s",
904 session->session_id);
908 osrfLogDebug(OSRF_LOG_MARK, "AppSession disconnecting from %s", session->remote_id );
910 osrfMessage* dis_msg = osrf_message_init( DISCONNECT, session->thread_trace, 1 );
911 _osrf_app_session_send( session, dis_msg );
912 session->state = OSRF_SESSION_DISCONNECTED;
914 osrfMessageFree( dis_msg );
915 osrf_app_session_reset_remote( session );
920 @brief Resend a request message, as specified by session and request id.
921 @param session Pointer to the osrfAppSession.
922 @param req_id Request ID for the request to be resent.
923 @return Zero if successful, or if the specified request cannot be found; 1 if the
924 request is already complete, or if the attempt to resend the message fails.
926 The choice of return codes may seem seem capricious, but at this writing nothing
927 pays any attention to the return code anyway.
929 int osrf_app_session_request_resend( osrfAppSession* session, int req_id ) {
930 osrfAppRequest* req = find_app_request( session, req_id );
935 } else if(!req->complete) {
936 osrfLogDebug( OSRF_LOG_MARK, "Resending request [%d]", req->request_id );
937 rc = _osrf_app_session_send( req->session, req->payload );
946 @brief Send one or more osrfMessages to the remote service or client.
947 @param session Pointer to the osrfAppSession responsible for sending the message(s).
948 @param msgs Pointer to an array of pointers to osrfMessages.
949 @param size How many messages to send.
950 @return 0 upon success, or -1 upon failure.
952 static int osrfAppSessionSendBatch( osrfAppSession* session, osrfMessage* msgs[], int size ) {
954 if( !(session && msgs && size > 0) ) return -1;
957 osrfMessage* msg = msgs[0];
961 // First grab and process any input messages, for any app session. This gives us
962 // a chance to see any CONNECT or DISCONNECT messages that may have arrived. We
963 // may also see some unrelated messages, but we have to process those sooner or
964 // later anyway, so we might as well do it now.
965 osrf_app_session_queue_wait( session, 0, NULL );
967 if(session->state != OSRF_SESSION_CONNECTED) {
969 if(session->stateless) { /* stateless session always send to the root listener */
970 osrf_app_session_reset_remote(session);
974 /* do an auto-connect if necessary */
975 if( ! session->stateless &&
976 (msg->m_type != CONNECT) &&
977 (msg->m_type != DISCONNECT) &&
978 (session->state != OSRF_SESSION_CONNECTED) ) {
980 if(!osrfAppSessionConnect( session ))
987 // Translate the collection of osrfMessages into a JSON array
988 char* string = osrfMessageSerializeBatch(msgs, size);
990 // Send the JSON as the payload of a transport_message
992 retval = osrfSendTransportPayload( session, string );
1000 @brief Wrap a given string in a transport message and send it.
1001 @param session Pointer to the osrfAppSession responsible for sending the message(s).
1002 @param payload A string to be sent via Jabber.
1003 @return 0 upon success, or -1 upon failure.
1005 In practice the payload is normally a JSON string, but this function assumes nothing
1008 int osrfSendTransportPayload( osrfAppSession* session, const char* payload ) {
1009 transport_message* t_msg = message_init(
1010 payload, "", session->session_id, session->remote_id, NULL );
1011 message_set_osrf_xid( t_msg, osrfLogGetXid() );
1013 int retval = client_send_message( session->transport_handle, t_msg );
1015 osrfLogError( OSRF_LOG_MARK, "client_send_message failed, exit()ing immediately" );
1019 osrfLogInfo(OSRF_LOG_MARK, "[%s] sent %d bytes of data to %s",
1020 session->remote_service, strlen( payload ), t_msg->recipient );
1022 osrfLogDebug( OSRF_LOG_MARK, "Sent: %s", payload );
1024 message_free( t_msg );
1029 @brief Send a single osrfMessage to the remote service or client.
1030 @param session Pointer to the osrfAppSession.
1031 @param msg Pointer to the osrfMessage to be sent.
1032 @return zero upon success, or 1 upon failure.
1034 A thin wrapper. Create an array of one element, and pass it to osrfAppSessionSendBatch().
1036 static int _osrf_app_session_send( osrfAppSession* session, osrfMessage* msg ){
1037 if( !(session && msg) )
1041 return - osrfAppSessionSendBatch( session, a, 1 );
1046 @brief Wait for any input messages to arrive, and process them as needed.
1047 @param session Pointer to the osrfAppSession whose transport_session we will use.
1048 @param timeout How many seconds to wait for the first input message.
1049 @param recvd Pointer to an boolean int. If you receive at least one message, set the boolean
1050 to true; otherwise set it to false.
1051 @return 0 upon success (even if a timeout occurs), or -1 upon failure.
1053 A thin wrapper for osrf_stack_process(). The timeout applies only to the first
1054 message; process subsequent messages if they are available, but don't wait for them.
1056 The first parameter identifies an osrfApp session, but all we really use it for is to
1057 get a pointer to the transport_session. Typically, a given process opens only a single
1058 transport_session (to talk to the Jabber server), and all app sessions in that process
1059 use the same transport_session.
1061 Hence this function indiscriminately waits for input messages for all osrfAppSessions
1062 tied to the same Jabber session, not just the one specified.
1064 Dispatch each message to the appropriate processing routine, depending on its type
1065 and contents, and on whether we're acting as a client or as a server for that message.
1066 For example, a response to a request may be appended to the input queue of the
1067 relevant request. A server session receiving a REQUEST message may execute the
1068 requested method. And so forth.
1070 int osrf_app_session_queue_wait( osrfAppSession* session, int timeout, int* recvd ){
1071 if(session == NULL) return 0;
1072 osrfLogDebug(OSRF_LOG_MARK, "AppSession in queue_wait with timeout %d", timeout );
1073 return osrf_stack_process(session->transport_handle, timeout, recvd);
1077 @brief Shut down and destroy an osrfAppSession.
1078 @param session Pointer to the osrfAppSession to be destroyed.
1080 If this is a client session, send a DISCONNECT message.
1082 Remove the session from the global session cache.
1084 Free all associated resources, including any pending osrfAppRequests.
1086 void osrfAppSessionFree( osrfAppSession* session ){
1087 if(session == NULL) return;
1091 osrfLogDebug(OSRF_LOG_MARK, "AppSession [%s] [%s] destroying self and deleting requests",
1092 session->remote_service, session->session_id );
1093 /* disconnect if we're a client */
1094 if(session->type == OSRF_SESSION_CLIENT
1095 && session->state != OSRF_SESSION_DISCONNECTED ) {
1096 osrfMessage* dis_msg = osrf_message_init( DISCONNECT, session->thread_trace, 1 );
1097 _osrf_app_session_send( session, dis_msg );
1098 osrfMessageFree(dis_msg);
1101 /* Remove self from the global session cache */
1103 osrfHashRemove( osrfAppSessionCache, session->session_id );
1105 /* Free the memory */
1107 if( session->userDataFree && session->userData )
1108 session->userDataFree(session->userData);
1110 if(session->session_locale)
1111 free(session->session_locale);
1113 free(session->remote_id);
1114 free(session->orig_remote_id);
1115 free(session->session_id);
1116 free(session->remote_service);
1118 // Free the request hash
1120 for( i = 0; i < OSRF_REQUEST_HASH_SIZE; ++i ) {
1121 osrfAppRequest* app = session->request_hash[ i ];
1123 osrfAppRequest* next = app->next;
1124 _osrf_app_request_free( app );
1129 if( session->outbuf )
1130 buffer_free( session->outbuf );
1136 @brief Wait for a response to a given request, subject to a timeout.
1137 @param session Pointer to the osrfAppSession that owns the request.
1138 @param req_id Request ID for the request.
1139 @param timeout How many seconds to wait.
1140 @return A pointer to the received osrfMessage if one arrives; otherwise NULL.
1142 A thin wrapper. Given a session and a request ID, look up the corresponding request
1143 and pass it to _osrf_app_request_recv().
1145 osrfMessage* osrfAppSessionRequestRecv(
1146 osrfAppSession* session, int req_id, int timeout ) {
1147 if(req_id < 0 || session == NULL)
1149 osrfAppRequest* req = find_app_request( session, req_id );
1150 return _osrf_app_request_recv( req, timeout );
1154 @brief In response to a specified request, send a payload of data to a client.
1155 @param ses Pointer to the osrfAppSession that owns the request.
1156 @param requestId Request ID of the osrfAppRequest.
1157 @param data Pointer to a jsonObject containing the data payload.
1158 @return 0 upon success, or -1 upon failure.
1160 Translate the jsonObject to a JSON string, and send it wrapped in a RESULT message.
1162 The only failure detected is if either of the two pointer parameters is NULL.
1164 int osrfAppRequestRespond( osrfAppSession* ses, int requestId, const jsonObject* data ) {
1165 if( !ses || ! data )
1168 osrfMessage* msg = osrf_message_init( RESULT, requestId, 1 );
1169 osrf_message_set_status_info( msg, NULL, "OK", OSRF_STATUS_OK );
1170 char* json = jsonObjectToJSON( data );
1172 osrf_message_set_result_content( msg, json );
1173 _osrf_app_session_send( ses, msg );
1176 osrfMessageFree( msg );
1183 @brief Send one or two messages to a client in response to a specified request.
1184 @param ses Pointer to the osrfAppSession that owns the request.
1185 @param requestId Request ID of the osrfAppRequest.
1186 @param data Pointer to a jsonObject containing the data payload.
1187 @return Zero in all cases.
1189 If the @a data parameter is not NULL, translate the jsonObject into a JSON string, and
1190 incorporate that string into a RESULT message as as the payload . Also build a STATUS
1191 message indicating that the response is complete. Send both messages bundled together
1192 in the same transport_message.
1194 If the @a data parameter is NULL, send only a STATUS message indicating that the response
1197 int osrfAppRequestRespondComplete(
1198 osrfAppSession* ses, int requestId, const jsonObject* data ) {
1200 osrfMessage* status = osrf_message_init( STATUS, requestId, 1);
1201 osrf_message_set_status_info( status, "osrfConnectStatus", "Request Complete",
1202 OSRF_STATUS_COMPLETE );
1205 osrfMessage* payload = osrf_message_init( RESULT, requestId, 1 );
1206 osrf_message_set_status_info( payload, NULL, "OK", OSRF_STATUS_OK );
1208 char* json = jsonObjectToJSON( data );
1209 osrf_message_set_result_content( payload, json );
1216 osrfAppSessionSendBatch( ses, ms, 2 );
1218 osrfMessageFree( payload );
1220 osrfAppSessionSendBatch( ses, &status, 1 );
1223 osrfMessageFree( status );
1229 @brief Send a STATUS message, for a specified request, back to the client.
1230 @param ses Pointer to the osrfAppSession connected to the client.
1231 @param type A numeric code denoting the status.
1232 @param name A string naming the status.
1233 @param reqId The request ID of the request.
1234 @param message A brief message describing the status.
1235 @return 0 upon success, or -1 upon failure.
1237 The only detected failure is when the @a ses parameter is NULL.
1239 int osrfAppSessionStatus( osrfAppSession* ses, int type,
1240 const char* name, int reqId, const char* message ) {
1243 osrfMessage* msg = osrf_message_init( STATUS, reqId, 1);
1244 osrf_message_set_status_info( msg, name, message, type );
1245 _osrf_app_session_send( ses, msg );
1246 osrfMessageFree( msg );
1253 @brief Free the global session cache.
1255 Note that the osrfHash that implements the global session cache does @em not have a
1256 callback function installed for freeing its cargo. As a result, any remaining
1257 osrfAppSessions are leaked, along with all the osrfAppRequests and osrfMessages they
1260 void osrfAppSessionCleanup( void ) {
1261 osrfHashFree(osrfAppSessionCache);
1262 osrfAppSessionCache = NULL;
1266 @brief Arrange for immediate termination of the process.
1267 @param ses Pointer to the current osrfAppSession.
1269 Typical use case: a server drone loses its database connection, thereby becoming useless.
1270 It terminates so that it will not receive further requests, being unable to service them.
1272 void osrfAppSessionPanic( osrfAppSession* ses ) {