1 /* This file is part of Pazpar2.
2 Copyright (C) Index Data
4 Pazpar2 is free software; you can redistribute it and/or modify it under
5 the terms of the GNU General Public License as published by the Free
6 Software Foundation; either version 2, or (at your option) any later
9 Pazpar2 is distributed in the hope that it will be useful, but WITHOUT ANY
10 WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
42 #include <yaz/marcdisp.h>
43 #include <yaz/comstack.h>
44 #include <yaz/tcpip.h>
45 #include <yaz/proto.h>
46 #include <yaz/readconf.h>
47 #include <yaz/pquery.h>
48 #include <yaz/otherinfo.h>
49 #include <yaz/yaz-util.h>
51 #include <yaz/query-charset.h>
52 #include <yaz/querytowrbuf.h>
53 #include <yaz/oid_db.h>
54 #include <yaz/diagbib1.h>
55 #include <yaz/snprintf.h>
56 #include <yaz/rpn2cql.h>
57 #include <yaz/rpn2solr.h>
58 #include <yaz/gettimeofday.h>
62 #include <yaz/timing.h>
67 #include "parameters.h"
69 #include "connection.h"
71 #include "relevance.h"
74 #define XDOC_CACHE_SIZE 100
76 static YAZ_MUTEX g_mutex = 0;
77 static int no_clients = 0;
79 static int client_use(int delta)
83 yaz_mutex_create(&g_mutex);
84 yaz_mutex_enter(g_mutex);
87 yaz_mutex_leave(g_mutex);
88 yaz_log(YLOG_DEBUG, "%s clients=%d",
89 delta == 0 ? "" : (delta > 0 ? "INC" : "DEC"), clients);
93 int clients_count(void)
98 /** \brief Represents client state for a connection to one search target */
100 struct session_database *database;
101 struct connection *connection;
102 struct session *session;
103 char *pquery; // Current search
104 char *cqlquery; // used for SRU targets only
105 char *addinfo; // diagnostic info for most resent error
109 int filtered; /* number of records ignored for local filtering */
110 int ingest_failures; /* number of records where XSLT/other failed */
111 int record_failures; /* number of records where ZOOM reported error */
117 struct suggestions *suggestions;
118 enum client_state state;
119 struct show_raw *show_raw;
120 ZOOM_resultset resultset;
124 facet_limits_t facet_limits;
140 int active; // whether this request has been sent to the server
146 void (*error_handler)(void *data, const char *addinfo);
147 void (*record_handler)(void *data, const char *buf, size_t sz);
149 struct show_raw *next;
152 static const char *client_states[] = {
158 "Client_Disconnected"
161 const char *client_get_state_str(struct client *cl)
163 return client_states[cl->state];
166 enum client_state client_get_state(struct client *cl)
171 void client_set_state_nb(struct client *cl, enum client_state st)
176 void client_set_state(struct client *cl, enum client_state st)
179 if (client_is_active(cl))
182 /* If client is going from being active to inactive and all clients
183 are now idle we fire a watch for the session . The assumption is
184 that session is not mutex locked if client is already active */
185 if (was_active && !client_is_active(cl) && cl->session)
188 int no_active = session_active_clients(cl->session);
189 yaz_log(YLOG_DEBUG, "%s: releasing watches on zero active: %d",
190 client_get_id(cl), no_active);
191 if (no_active == 0) {
192 session_alert_watch(cl->session, SESSION_WATCH_SHOW);
193 session_alert_watch(cl->session, SESSION_WATCH_BYTARGET);
194 session_alert_watch(cl->session, SESSION_WATCH_TERMLIST);
195 session_alert_watch(cl->session, SESSION_WATCH_SHOW_PREF);
200 static void client_init_xdoc(struct client *cl)
204 cl->xdoc = xmalloc(sizeof(*cl->xdoc) * XDOC_CACHE_SIZE);
205 for (i = 0; i < XDOC_CACHE_SIZE; i++)
209 static void client_destroy_xdoc(struct client *cl)
214 for (i = 0; i < XDOC_CACHE_SIZE; i++)
216 xmlFreeDoc(cl->xdoc[i]);
220 xmlDoc *client_get_xdoc(struct client *cl, int record_no)
223 if (record_no >= 0 && record_no < XDOC_CACHE_SIZE)
224 return cl->xdoc[record_no];
228 void client_store_xdoc(struct client *cl, int record_no, xmlDoc *xdoc)
231 if (record_no >= 0 && record_no < XDOC_CACHE_SIZE)
233 if (cl->xdoc[record_no])
234 xmlFreeDoc(cl->xdoc[record_no]);
235 cl->xdoc[record_no] = xdoc;
244 static void client_show_raw_error(struct client *cl, const char *addinfo);
246 struct connection *client_get_connection(struct client *cl)
248 return cl->connection;
251 struct session_database *client_get_database(struct client *cl)
256 struct session *client_get_session(struct client *cl)
261 static void client_send_raw_present(struct client *cl);
262 static int nativesyntax_to_type(const char *s, char *type, ZOOM_record rec);
264 static void client_show_immediate(
265 ZOOM_resultset resultset, struct session_database *sdb, int position,
267 void (*error_handler)(void *data, const char *addinfo),
268 void (*record_handler)(void *data, const char *buf, size_t sz),
270 const char *nativesyntax)
279 error_handler(data, "no resultset");
282 rec = ZOOM_resultset_record_immediate(resultset, position-1);
285 error_handler(data, "no record");
288 nativesyntax_to_type(nativesyntax, type, rec);
289 buf = ZOOM_record_get(rec, type, &len);
292 error_handler(data, "no record");
295 record_handler(data, buf, len);
299 int client_show_raw_begin(struct client *cl, int position,
300 const char *syntax, const char *esn,
302 void (*error_handler)(void *data, const char *addinfo),
303 void (*record_handler)(void *data, const char *buf,
306 const char *nativesyntax)
311 nativesyntax = "raw";
314 struct session_database *sdb = client_get_database(cl);
315 nativesyntax = session_setting_oneval(sdb, PZ_NATIVESYNTAX);
319 if (syntax == 0 && esn == 0)
320 client_show_immediate(cl->resultset, client_get_database(cl),
322 error_handler, record_handler,
323 binary, nativesyntax);
326 struct show_raw *rr, **rrp;
332 rr = xmalloc(sizeof(*rr));
333 rr->position = position;
336 rr->error_handler = error_handler;
337 rr->record_handler = record_handler;
340 rr->syntax = xstrdup(syntax);
344 rr->esn = xstrdup(esn);
348 assert(nativesyntax);
349 rr->nativesyntax = xstrdup(nativesyntax);
353 for (rrp = &cl->show_raw; *rrp; rrp = &(*rrp)->next)
357 if (cl->state == Client_Failed)
359 client_show_raw_error(cl, "client failed");
361 else if (cl->state == Client_Disconnected)
363 client_show_raw_error(cl, "client disconnected");
367 client_send_raw_present(cl);
373 static void client_show_raw_delete(struct show_raw *r)
377 xfree(r->nativesyntax);
381 void client_show_raw_remove(struct client *cl, void *data)
383 struct show_raw *rr = data;
384 struct show_raw **rrp = &cl->show_raw;
390 client_show_raw_delete(rr);
394 static void client_show_raw_dequeue(struct client *cl)
396 struct show_raw *rr = cl->show_raw;
398 cl->show_raw = rr->next;
399 client_show_raw_delete(rr);
402 static void client_show_raw_error(struct client *cl, const char *addinfo)
406 cl->show_raw->error_handler(cl->show_raw->data, addinfo);
407 client_show_raw_dequeue(cl);
411 static void client_send_raw_present(struct client *cl)
413 struct session_database *sdb = client_get_database(cl);
414 struct connection *co = client_get_connection(cl);
415 ZOOM_resultset set = cl->resultset;
417 int offset = cl->show_raw->position;
418 const char *syntax = 0;
419 const char *elements = 0;
421 assert(cl->show_raw);
424 yaz_log(YLOG_DEBUG, "%s: trying to present %d record(s) from %d",
425 client_get_id(cl), 1, offset);
427 if (cl->show_raw->syntax)
428 syntax = cl->show_raw->syntax;
430 syntax = session_setting_oneval(sdb, PZ_REQUESTSYNTAX);
431 ZOOM_resultset_option_set(set, "preferredRecordSyntax", syntax);
433 if (cl->show_raw->esn)
434 elements = cl->show_raw->esn;
436 elements = session_setting_oneval(sdb, PZ_ELEMENTS);
437 if (elements && *elements)
438 ZOOM_resultset_option_set(set, "elementSetName", elements);
440 ZOOM_resultset_records(set, 0, offset-1, 1);
441 cl->show_raw->active = 1;
443 connection_continue(co);
446 static int nativesyntax_to_type(const char *s, char *type,
451 if (!strncmp(s, "iso2709", 7))
453 const char *cp = strchr(s, ';');
454 yaz_snprintf(type, 80, "xml; charset=%s", cp ? cp+1 : "marc-8s");
456 else if (!strncmp(s, "txml", 4))
458 const char *cp = strchr(s, ';');
459 yaz_snprintf(type, 80, "txml; charset=%s", cp ? cp+1 : "marc-8s");
461 else /* pass verbatim to ZOOM - including "xml" */
465 else /* attempt to deduce structure */
467 const char *syntax = ZOOM_record_get(rec, "syntax", NULL);
470 if (!strcmp(syntax, "XML"))
475 else if (!strcmp(syntax, "USmarc") || !strcmp(syntax, "MARC21"))
477 strcpy(type, "xml; charset=marc8-s");
487 * TODO Consider thread safety!!!
490 static void client_report_facets(struct client *cl, ZOOM_resultset rs)
492 struct session_database *sdb = client_get_database(cl);
493 ZOOM_facet_field *facets = ZOOM_resultset_facets(rs);
497 struct session *se = client_get_session(cl);
498 int facet_num = ZOOM_resultset_facets_size(rs);
501 for (s = sdb->settings[PZ_FACETMAP]; s; s = s->next)
503 const char *p = strchr(s->name + 3, ':');
504 if (p && p[1] && s->value && s->value[0])
507 p++; /* p now holds logical facet name */
508 for (facet_idx = 0; facet_idx < facet_num; facet_idx++)
510 const char *native_name =
511 ZOOM_facet_field_name(facets[facet_idx]);
512 if (native_name && !strcmp(s->value, native_name))
516 ZOOM_facet_field_term_count(facets[facet_idx]);
517 for (term_idx = 0; term_idx < term_num; term_idx++ )
521 ZOOM_facet_field_get_term(facets[facet_idx],
524 add_facet(se, p, term, freq);
534 static void ingest_raw_record(struct client *cl, ZOOM_record rec)
540 nativesyntax_to_type(cl->show_raw->nativesyntax, type, rec);
541 buf = ZOOM_record_get(rec, type, &len);
542 cl->show_raw->record_handler(cl->show_raw->data, buf, len);
543 client_show_raw_dequeue(cl);
546 struct suggestions* client_suggestions_create(const char* suggestions_string);
547 static void client_suggestions_destroy(struct client *cl);
549 void client_search_response(struct client *cl)
551 struct connection *co = cl->connection;
552 ZOOM_connection link = connection_get_link(co);
553 ZOOM_resultset resultset = cl->resultset;
554 struct session *se = client_get_session(cl);
556 const char *error, *addinfo = 0;
558 if (ZOOM_connection_error(link, &error, &addinfo))
561 session_log(se, YLOG_WARN, "%s: Error %s (%s)",
562 client_get_id(cl), error, addinfo);
563 client_set_state(cl, Client_Error);
567 client_report_facets(cl, resultset);
568 cl->record_offset = cl->startrecs;
569 cl->hits = ZOOM_resultset_size(resultset);
570 session_log(se, YLOG_LOG, "%s: hits: " ODR_INT_PRINTF,
571 client_get_id(cl), cl->hits);
573 client_suggestions_destroy(cl);
575 client_suggestions_create(ZOOM_resultset_option_get(
576 resultset, "suggestions"));
580 void client_got_records(struct client *cl)
582 struct session *se = cl->session;
586 /* TODO possible threading issue. Session can have been destroyed */
587 if (session_is_preferred_clients_ready(se))
588 session_alert_watch(se, SESSION_WATCH_SHOW_PREF);
590 if (reclist_get_num_records(se->reclist) > 0)
593 session_alert_watch(se, SESSION_WATCH_SHOW);
594 session_alert_watch(se, SESSION_WATCH_BYTARGET);
595 session_alert_watch(se, SESSION_WATCH_TERMLIST);
596 session_alert_watch(se, SESSION_WATCH_RECORD);
602 static void client_record_ingest(struct client *cl)
604 const char *msg, *addinfo;
606 ZOOM_resultset resultset = cl->resultset;
607 struct session *se = client_get_session(cl);
609 int offset = cl->record_offset + 1; /* 0 versus 1 numbered offsets */
611 xdoc = client_get_xdoc(cl, offset);
616 NMEM nmem = nmem_create();
617 int rc = ingest_xml_record(cl, xdoc, offset, nmem, 1);
620 session_log(se, YLOG_WARN,
621 "%s: #%d: failed to ingest xdoc",
622 client_get_id(cl), offset);
623 cl->ingest_failures++;
630 else if ((rec = ZOOM_resultset_record_immediate(resultset,
633 if (cl->session == 0)
635 else if (ZOOM_record_error(rec, &msg, &addinfo, 0))
637 session_log(se, YLOG_WARN, "Record error %s (%s): %s #%d",
638 msg, addinfo, client_get_id(cl), offset);
639 cl->record_failures++;
643 struct session_database *sdb = client_get_database(cl);
644 NMEM nmem = nmem_create();
648 const char *s = session_setting_oneval(sdb, PZ_NATIVESYNTAX);
649 if (nativesyntax_to_type(s, type, rec))
650 session_log(se, YLOG_WARN, "Failed to determine record type");
651 xmlrec = ZOOM_record_get(rec, type, NULL);
654 const char *rec_syn = ZOOM_record_get(rec, "syntax", NULL);
655 session_log(se, YLOG_WARN, "%s: #%d: ZOOM_record_get failed",
656 client_get_id(cl), offset);
657 session_log(se, YLOG_LOG, "pz:nativesyntax=%s . "
658 "ZOOM record type=%s . Actual record syntax=%s",
659 s ? s : "null", type,
660 rec_syn ? rec_syn : "null");
661 cl->ingest_failures++;
665 /* OK = 0, -1 = failure, -2 = Filtered */
666 int rc = ingest_record(cl, xmlrec, offset, nmem);
669 const char *rec_syn = ZOOM_record_get(rec, "syntax", NULL);
670 session_log(se, YLOG_WARN,
671 "%s: #%d: failed to ingest record",
672 client_get_id(cl), offset);
673 session_log(se, YLOG_LOG, "pz:nativesyntax=%s . "
674 "ZOOM record type=%s . Actual record syntax=%s",
675 s ? s : "null", type,
676 rec_syn ? rec_syn : "null");
677 cl->ingest_failures++;
687 session_log(se, YLOG_WARN, "Got NULL record from %s #%d",
688 client_get_id(cl), offset);
693 void client_record_response(struct client *cl, int *got_records)
695 struct connection *co = cl->connection;
696 ZOOM_connection link = connection_get_link(co);
697 ZOOM_resultset resultset = cl->resultset;
698 const char *error, *addinfo;
700 if (ZOOM_connection_error(link, &error, &addinfo))
702 struct session *se = client_get_session(cl);
703 session_log(se, YLOG_WARN, "%s: Error %s (%s)",
704 client_get_id(cl), error, addinfo);
705 client_set_state(cl, Client_Error);
709 if (cl->show_raw && cl->show_raw->active)
712 if ((rec = ZOOM_resultset_record_immediate(
713 resultset, cl->show_raw->position-1)))
715 cl->show_raw->active = 0;
716 ingest_raw_record(cl, rec);
720 yaz_log(YLOG_WARN, "Expected record, but got NULL, offset=%d",
721 cl->show_raw->position-1);
726 client_record_ingest(cl);
732 int client_reingest(struct client *cl)
734 int i = cl->startrecs;
735 int to = cl->record_offset;
736 cl->record_failures = cl->ingest_failures = cl->filtered = 0;
738 cl->record_offset = i;
740 client_record_ingest(cl);
744 static void client_set_facets_request(struct client *cl, ZOOM_connection link)
746 struct session_database *sdb = client_get_database(cl);
748 WRBUF w = wrbuf_alloc();
752 for (s = sdb->settings[PZ_FACETMAP]; s; s = s->next)
754 const char *p = strchr(s->name + 3, ':');
757 yaz_log(YLOG_WARN, "Malformed facetmap name: %s", s->name);
759 else if (s->value && s->value[0])
761 wrbuf_puts(w, "@attr 1=");
762 yaz_encode_pqf_term(w, s->value, strlen(s->value));
767 yaz_log(YLOG_DEBUG, "using facets str: %s", wrbuf_cstr(w));
768 ZOOM_connection_option_set(link, "facets",
769 wrbuf_len(w) ? wrbuf_cstr(w) : 0);
773 int client_has_facet(struct client *cl, const char *name)
775 struct session_database *sdb = client_get_database(cl);
778 for (s = sdb->settings[PZ_FACETMAP]; s; s = s->next)
780 const char *p = strchr(s->name + 3, ':');
781 if (p && !strcmp(name, p + 1))
787 static const char *get_strategy_plus_sort(struct client *l, const char *field)
789 struct session_database *sdb = client_get_database(l);
792 const char *strategy_plus_sort = 0;
794 for (s = sdb->settings[PZ_SORTMAP]; s; s = s->next)
796 char *p = strchr(s->name + 3, ':');
799 yaz_log(YLOG_WARN, "Malformed sortmap name: %s", s->name);
803 if (!strcmp(p, field))
805 strategy_plus_sort = s->value;
809 return strategy_plus_sort;
812 void client_update_show_stat(struct client *cl, int cmd)
815 cl->show_stat_no = 0;
820 int client_fetch_more(struct client *cl)
822 struct session_database *sdb = client_get_database(cl);
825 int number = cl->hits - cl->record_offset;
827 str = session_setting_oneval(sdb, PZ_EXTENDRECS);
831 extend_recs = atoi(str);
833 yaz_log(YLOG_LOG, "cl=%s show_stat_no=%d got=%d",
834 client_get_id(cl), cl->show_stat_no, cl->record_offset);
835 if (cl->show_stat_no < cl->record_offset)
837 yaz_log(YLOG_LOG, "cl=%s Trying to fetch more", client_get_id(cl));
839 if (number > extend_recs)
840 number = extend_recs;
843 ZOOM_resultset set = cl->resultset;
844 struct connection *co = client_get_connection(cl);
846 str = session_setting_oneval(sdb, PZ_REQUESTSYNTAX);
847 ZOOM_resultset_option_set(set, "preferredRecordSyntax", str);
848 str = session_setting_oneval(sdb, PZ_ELEMENTS);
850 ZOOM_resultset_option_set(set, "elementSetName", str);
852 ZOOM_resultset_records(set, 0, cl->record_offset, number);
853 client_set_state(cl, Client_Working);
854 connection_continue(co);
859 yaz_log(YLOG_LOG, "cl=%s. OK no more in total set", client_get_id(cl));
864 int client_parse_init(struct client *cl, int same_search)
866 cl->same_search = same_search;
871 * TODO consider how to extend the range
873 int client_parse_range(struct client *cl, const char *startrecs,
876 if (maxrecs && atoi(maxrecs) != cl->maxrecs)
879 cl->maxrecs = atoi(maxrecs);
882 if (startrecs && atoi(startrecs) != cl->startrecs)
885 cl->startrecs = atoi(startrecs);
891 int client_start_search(struct client *cl)
893 struct session_database *sdb = client_get_database(cl);
894 struct connection *co = 0;
895 ZOOM_connection link = 0;
896 struct session *se = client_get_session(cl);
898 const char *opt_piggyback = session_setting_oneval(sdb, PZ_PIGGYBACK);
899 const char *opt_queryenc = session_setting_oneval(sdb, PZ_QUERYENCODING);
900 const char *opt_elements = session_setting_oneval(sdb, PZ_ELEMENTS);
901 const char *opt_requestsyn = session_setting_oneval(sdb, PZ_REQUESTSYNTAX);
902 const char *opt_maxrecs = session_setting_oneval(sdb, PZ_MAXRECS);
903 const char *opt_sru = session_setting_oneval(sdb, PZ_SRU);
904 const char *opt_sort = session_setting_oneval(sdb, PZ_SORT);
905 const char *opt_preferred = session_setting_oneval(sdb, PZ_PREFERRED);
906 const char *extra_args = session_setting_oneval(sdb, PZ_EXTRA_ARGS);
907 const char *opt_present_chunk = session_setting_oneval(sdb, PZ_PRESENT_CHUNK);
908 const char *opt_timeout = session_setting_oneval(sdb, PZ_TIMEOUT);
910 char maxrecs_str[24], startrecs_str[24], present_chunk_str[24];
912 int present_chunk = 20; // Default chunk size
913 int rc_prep_connection;
914 int operation_timeout = se->service->z3950_operation_timeout;
917 cl->record_failures = cl->ingest_failures = cl->filtered = 0;
919 yaz_gettimeofday(&tval);
922 if (opt_timeout && *opt_timeout)
923 operation_timeout = atoi(opt_timeout);
925 if (opt_present_chunk && strcmp(opt_present_chunk,"")) {
926 present_chunk = atoi(opt_present_chunk);
927 yaz_log(YLOG_DEBUG, "Present chunk set to %d", present_chunk);
930 client_prep_connection(cl, operation_timeout,
931 se->service->z3950_session_timeout,
932 se->service->server->iochan_man,
934 /* Nothing has changed and we already have a result */
935 if (cl->same_search == 1 && rc_prep_connection == 2)
937 session_log(se, YLOG_LOG, "%s: reuse result", client_get_id(cl));
938 client_report_facets(cl, cl->resultset);
939 return client_reingest(cl);
941 else if (!rc_prep_connection)
943 session_log(se, YLOG_LOG, "%s: postponing search: No connection",
945 client_set_state_nb(cl, Client_Working);
948 co = client_get_connection(cl);
950 link = connection_get_link(co);
953 session_log(se, YLOG_LOG, "%s: new search", client_get_id(cl));
955 client_destroy_xdoc(cl);
956 client_init_xdoc(cl);
958 if (extra_args && *extra_args)
959 ZOOM_connection_option_set(link, "extraArgs", extra_args);
962 cl->preferred = atoi(opt_preferred);
964 yaz_log(YLOG_LOG, "Target %s has preferred status: %d",
965 client_get_id(cl), cl->preferred);
969 ZOOM_connection_option_set(link, "piggyback", opt_piggyback);
971 ZOOM_connection_option_set(link, "piggyback", "1");
973 ZOOM_connection_option_set(link, "rpnCharset", opt_queryenc);
974 if (*opt_sru && *opt_elements)
975 ZOOM_connection_option_set(link, "schema", opt_elements);
976 else if (*opt_elements)
977 ZOOM_connection_option_set(link, "elementSetName", opt_elements);
979 ZOOM_connection_option_set(link, "preferredRecordSyntax", opt_requestsyn);
981 if (opt_maxrecs && *opt_maxrecs)
983 cl->maxrecs = atoi(opt_maxrecs);
986 /* convert back to string representation used in ZOOM API */
987 sprintf(maxrecs_str, "%d", cl->maxrecs);
988 ZOOM_connection_option_set(link, "count", maxrecs_str);
990 /* A present_chunk less than 1 will disable chunking. */
991 if (present_chunk > 0 && cl->maxrecs > present_chunk) {
992 sprintf(present_chunk_str, "%d", present_chunk);
993 ZOOM_connection_option_set(link, "presentChunk", present_chunk_str);
994 yaz_log(YLOG_DEBUG, "Present chunk set to %s", present_chunk_str);
997 ZOOM_connection_option_set(link, "presentChunk", maxrecs_str);
998 yaz_log(YLOG_DEBUG, "Present chunk set to %s (maxrecs)", maxrecs_str);
1000 sprintf(startrecs_str, "%d", cl->startrecs);
1001 ZOOM_connection_option_set(link, "start", startrecs_str);
1003 /* TODO Verify does it break something for CQL targets(non-SOLR) ? */
1004 /* facets definition is in PQF */
1005 client_set_facets_request(cl, link);
1007 query = ZOOM_query_create();
1010 session_log(se, YLOG_LOG, "%s: Search CQL: %s", client_get_id(cl),
1012 ZOOM_query_cql(query, cl->cqlquery);
1014 ZOOM_query_sortby(query, opt_sort);
1018 session_log(se, YLOG_LOG, "%s: Search PQF: %s", client_get_id(cl),
1020 ZOOM_query_prefix(query, cl->pquery);
1022 if (cl->sort_strategy && cl->sort_criteria) {
1023 yaz_log(YLOG_LOG, "Client %s: "
1024 "Set ZOOM sort strategy and criteria: %s %s",
1025 client_get_id(cl), cl->sort_strategy, cl->sort_criteria);
1026 ZOOM_query_sortby2(query, cl->sort_strategy, cl->sort_criteria);
1029 yaz_log(YLOG_DEBUG,"Client %s: Starting search", client_get_id(cl));
1030 client_set_state(cl, Client_Working);
1032 cl->record_offset = 0;
1033 rs = ZOOM_connection_search(link, query);
1034 ZOOM_query_destroy(query);
1035 ZOOM_resultset_destroy(cl->resultset);
1037 connection_continue(co);
1041 struct client *client_create(const char *id)
1043 struct client *cl = xmalloc(sizeof(*cl));
1054 cl->record_offset = 0;
1057 cl->state = Client_Disconnected;
1060 cl->suggestions = 0;
1062 pazpar2_mutex_create(&cl->mutex, "client");
1065 cl->facet_limits = 0;
1066 cl->sort_strategy = 0;
1067 cl->sort_criteria = 0;
1069 cl->id = xstrdup(id);
1070 client_init_xdoc(cl);
1073 yaz_log(YLOG_DEBUG, "client_create c=%p %s", cl, id);
1077 void client_lock(struct client *c)
1079 yaz_mutex_enter(c->mutex);
1082 void client_unlock(struct client *c)
1084 yaz_mutex_leave(c->mutex);
1087 void client_incref(struct client *c)
1089 pazpar2_incref(&c->ref_count, c->mutex);
1090 yaz_log(YLOG_DEBUG, "client_incref c=%p %s cnt=%d",
1091 c, client_get_id(c), c->ref_count);
1094 int client_destroy(struct client *c)
1098 yaz_log(YLOG_DEBUG, "client_destroy c=%p %s cnt=%d",
1099 c, client_get_id(c), c->ref_count);
1100 if (!pazpar2_decref(&c->ref_count, c->mutex))
1111 xfree(c->sort_strategy);
1112 xfree(c->sort_criteria);
1113 assert(!c->connection);
1114 facet_limits_destroy(c->facet_limits);
1116 client_destroy_xdoc(c);
1119 ZOOM_resultset_destroy(c->resultset);
1121 yaz_mutex_destroy(&c->mutex);
1130 void client_set_connection(struct client *cl, struct connection *con)
1133 ZOOM_resultset_release(cl->resultset);
1136 assert(cl->connection == 0);
1137 cl->connection = con;
1143 cl->connection = con;
1149 void client_disconnect(struct client *cl)
1151 if (cl->state != Client_Idle)
1152 client_set_state(cl, Client_Disconnected);
1153 client_set_connection(cl, 0);
1156 void client_stop(struct client *cl)
1159 if (cl->state == Client_Working || cl->state == Client_Connecting)
1161 yaz_log(YLOG_LOG, "client_stop: %s release", client_get_id(cl));
1164 connection_release2(cl->connection);
1165 assert(cl->ref_count > 1);
1169 cl->state = Client_Disconnected;
1172 yaz_log(YLOG_LOG, "client_stop: %s ignore", client_get_id(cl));
1176 // Initialize CCL map for a target
1177 static CCL_bibset prepare_cclmap(struct client *cl, CCL_bibset base_bibset)
1179 struct session_database *sdb = client_get_database(cl);
1186 res = ccl_qual_dup(base_bibset);
1188 res = ccl_qual_mk();
1189 for (s = sdb->settings[PZ_CCLMAP]; s; s = s->next)
1191 const char *addinfo = 0;
1192 char *p = strchr(s->name + 3, ':');
1195 WRBUF w = wrbuf_alloc();
1196 wrbuf_printf(w, "Malformed cclmap. name=%s", s->name);
1197 yaz_log(YLOG_WARN, "%s: %s", client_get_id(cl), wrbuf_cstr(w));
1198 client_set_diagnostic(cl, ZOOM_ERROR_CCL_CONFIG,
1199 ZOOM_diag_str(ZOOM_ERROR_CCL_CONFIG),
1201 client_set_state_nb(cl, Client_Error);
1207 if (ccl_qual_fitem2(res, s->value, p, &addinfo))
1209 WRBUF w = wrbuf_alloc();
1211 wrbuf_printf(w, "Malformed cclmap. name=%s: value=%s (%s)",
1212 s->name, p, addinfo);
1213 yaz_log(YLOG_WARN, "%s: %s", client_get_id(cl), wrbuf_cstr(w));
1214 client_set_diagnostic(cl, ZOOM_ERROR_CCL_CONFIG,
1215 ZOOM_diag_str(ZOOM_ERROR_CCL_CONFIG),
1217 client_set_state_nb(cl, Client_Error);
1226 // returns a xmalloced CQL query corresponding to the pquery in client
1227 static char *make_cqlquery(struct client *cl, Z_RPNQuery *zquery)
1229 cql_transform_t cqlt = cql_transform_create();
1231 WRBUF wrb = wrbuf_alloc();
1234 if ((status = cql_transform_rpn2cql_wrbuf(cqlt, wrb, zquery)))
1236 yaz_log(YLOG_WARN, "Failed to generate CQL query, code=%d", status);
1240 r = xstrdup(wrbuf_cstr(wrb));
1243 cql_transform_close(cqlt);
1247 // returns a xmalloced SOLR query corresponding to the pquery in client
1248 // TODO Could prob. be merge with the similar make_cqlquery
1249 static char *make_solrquery(struct client *cl, Z_RPNQuery *zquery)
1251 solr_transform_t sqlt = solr_transform_create();
1253 WRBUF wrb = wrbuf_alloc();
1256 if ((status = solr_transform_rpn2solr_wrbuf(sqlt, wrb, zquery)))
1258 yaz_log(YLOG_WARN, "Failed to generate SOLR query, code=%d", status);
1262 r = xstrdup(wrbuf_cstr(wrb));
1265 solr_transform_close(sqlt);
1269 const char *client_get_facet_limit_local(struct client *cl,
1270 struct session_database *sdb,
1272 NMEM nmem, int *num, char ***values)
1274 const char *name = 0;
1275 const char *value = 0;
1276 for (; (name = facet_limits_get(cl->facet_limits, *l, &value)); (*l)++)
1278 struct setting *s = 0;
1280 for (s = sdb->settings[PZ_LIMITMAP]; s; s = s->next)
1282 const char *p = strchr(s->name + 3, ':');
1283 if (p && !strcmp(p + 1, name) && s->value)
1287 nmem_strsplit_escape2(nmem, ",", s->value, &cvalues,
1289 for (j = 0; j < cnum; j++)
1291 const char *cvalue = cvalues[j];
1292 while (*cvalue == ' ')
1294 if (!strncmp(cvalue, "local:", 6))
1296 const char *cp = cvalue + 6;
1299 nmem_strsplit_escape2(nmem, "|", value, values,
1302 return *cp ? cp : name;
1311 static int apply_limit(struct session_database *sdb,
1312 facet_limits_t facet_limits,
1313 WRBUF w_pqf, CCL_bibset ccl_map,
1314 struct conf_service *service)
1321 NMEM nmem_tmp = nmem_create();
1322 for (i = 0; (name = facet_limits_get(facet_limits, i, &value)); i++)
1324 struct setting *s = 0;
1325 nmem_reset(nmem_tmp);
1326 /* name="pz:limitmap:author" value="rpn:@attr 1=4|local:other" */
1327 for (s = sdb->settings[PZ_LIMITMAP]; s; s = s->next)
1329 const char *p = strchr(s->name + 3, ':');
1330 if (p && !strcmp(p + 1, name) && s->value)
1336 nmem_strsplit_escape2(nmem_tmp, "|", value, &values,
1339 nmem_strsplit_escape2(nmem_tmp, ",", s->value, &cvalues,
1342 for (j = 0; ret == 0 && j < cnum; j++)
1344 const char *cvalue = cvalues[j];
1345 while (*cvalue == ' ')
1347 if (!strncmp(cvalue, "rpn:", 4))
1349 const char *pqf = cvalue + 4;
1350 wrbuf_puts(w_pqf, "@and ");
1351 wrbuf_puts(w_pqf, pqf);
1352 wrbuf_puts(w_pqf, " ");
1353 for (i = 0; i < num; i++)
1356 wrbuf_puts(w_pqf, "@or ");
1357 yaz_encode_pqf_term(w_pqf, values[i],
1361 else if (!strncmp(cvalue, "ccl:", 4))
1363 const char *ccl = cvalue + 4;
1364 WRBUF ccl_w = wrbuf_alloc();
1365 for (i = 0; i < num; i++)
1368 struct ccl_rpn_node *cn;
1369 wrbuf_rewind(ccl_w);
1370 wrbuf_puts(ccl_w, ccl);
1371 wrbuf_putc(ccl_w, '=');
1372 if (strchr(values[i], ' '))
1373 wrbuf_putc(ccl_w, '\"');
1374 wrbuf_puts(ccl_w, values[i]);
1375 if (strchr(values[i], ' '))
1376 wrbuf_putc(ccl_w, '\"');
1377 cn = ccl_find_str(ccl_map, wrbuf_cstr(ccl_w),
1382 wrbuf_printf(w_pqf, "@and ");
1384 /* or multiple values.. could be bad if last
1385 CCL parse fails, but this is unlikely to
1388 wrbuf_printf(w_pqf, "@or ");
1389 ccl_pquery(w_pqf, cn);
1393 wrbuf_destroy(ccl_w);
1395 else if (!strncmp(cvalue, "local:", 6)) {
1400 yaz_log(YLOG_WARN, "Target %s: Bad limitmap '%s'",
1401 sdb->database->id, cvalue);
1402 ret = -1; /* bad limitmap */
1411 for (i = 0; i < service->num_metadata; i++)
1413 struct conf_metadata *md = service->metadata + i;
1414 if (!strcmp(md->name, name) && md->limitcluster)
1416 yaz_log(YLOG_LOG, "limitcluster in use for %s",
1421 if (i == service->num_metadata)
1423 yaz_log(YLOG_WARN, "Target %s: limit %s used, but no limitmap defined",
1424 (sdb->database ? sdb->database->id : "<no id>"), name);
1428 nmem_destroy(nmem_tmp);
1432 // Parse the query given the settings specific to this client
1433 // client variable same_search is set as below as well as returned:
1434 // 0 if query is OK but different from before
1435 // 1 if query is OK but same as before
1436 // return -1 on query error
1437 // return -2 on limit error
1438 int client_parse_query(struct client *cl, const char *query,
1439 facet_limits_t facet_limits, const char **error_msg)
1441 struct session *se = client_get_session(cl);
1442 struct conf_service *service = se->service;
1443 struct session_database *sdb = client_get_database(cl);
1444 struct ccl_rpn_node *cn;
1447 CCL_bibset ccl_map = prepare_cclmap(cl, service->ccl_bibset);
1448 const char *sru = session_setting_oneval(sdb, PZ_SRU);
1449 const char *pqf_prefix = session_setting_oneval(sdb, PZ_PQF_PREFIX);
1450 const char *pqf_strftime = session_setting_oneval(sdb, PZ_PQF_STRFTIME);
1451 const char *query_syntax = session_setting_oneval(sdb, PZ_QUERY_SYNTAX);
1459 w_ccl = wrbuf_alloc();
1460 wrbuf_puts(w_ccl, query);
1462 w_pqf = wrbuf_alloc();
1465 wrbuf_puts(w_pqf, pqf_prefix);
1466 wrbuf_puts(w_pqf, " ");
1469 if (apply_limit(sdb, facet_limits, w_pqf, ccl_map, service))
1471 ccl_qual_rm(&ccl_map);
1475 facet_limits_destroy(cl->facet_limits);
1476 cl->facet_limits = facet_limits_dup(facet_limits);
1478 yaz_log(YLOG_LOG, "Client %s: CCL query: %s limit: %s",
1479 client_get_id(cl), wrbuf_cstr(w_ccl), wrbuf_cstr(w_pqf));
1480 cn = ccl_find_str(ccl_map, wrbuf_cstr(w_ccl), &cerror, &cpos);
1481 ccl_qual_rm(&ccl_map);
1485 *error_msg = ccl_err_msg(cerror);
1486 client_set_state(cl, Client_Error);
1487 session_log(se, YLOG_WARN, "Client %s: Failed to parse CCL query '%s'",
1490 wrbuf_destroy(w_ccl);
1491 wrbuf_destroy(w_pqf);
1494 wrbuf_destroy(w_ccl);
1496 if (!pqf_strftime || !*pqf_strftime)
1497 ccl_pquery(w_pqf, cn);
1500 time_t cur_time = time(0);
1501 struct tm *tm = localtime(&cur_time);
1503 const char *cp = tmp_str;
1505 /* see man strftime(3) for things .. In particular %% gets converted
1506 to %.. And That's our original query .. */
1507 strftime(tmp_str, sizeof(tmp_str)-1, pqf_strftime, tm);
1511 ccl_pquery(w_pqf, cn);
1513 wrbuf_putc(w_pqf, cp[0]);
1517 /* Compares query and limit with old one. If different we need to research */
1518 if (!cl->pquery || strcmp(cl->pquery, wrbuf_cstr(w_pqf)))
1521 session_log(se, YLOG_LOG, "Client %s: "
1522 "Re-search due query/limit change: %s to %s",
1523 client_get_id(cl), cl->pquery, wrbuf_cstr(w_pqf));
1525 cl->pquery = xstrdup(wrbuf_cstr(w_pqf));
1526 // return value is no longer used.
1528 // Need to (re)search
1531 wrbuf_destroy(w_pqf);
1533 xfree(cl->cqlquery);
1536 odr_out = odr_createmem(ODR_ENCODE);
1537 zquery = p_query_rpn(odr_out, cl->pquery);
1541 session_log(se, YLOG_WARN, "Invalid PQF query for Client %s: %s",
1542 client_get_id(cl), cl->pquery);
1544 *error_msg = "Invalid PQF after CCL to PQF conversion";
1548 session_log(se, YLOG_LOG, "PQF for Client %s: %s",
1549 client_get_id(cl), cl->pquery);
1551 /* Support for PQF on SRU targets. */
1552 if (strcmp(query_syntax, "pqf") != 0 && *sru)
1554 if (!strcmp(sru, "solr"))
1555 cl->cqlquery = make_solrquery(cl, zquery);
1557 cl->cqlquery = make_cqlquery(cl, zquery);
1560 *error_msg = "Cannot convert PQF to Solr/CQL";
1564 session_log(se, YLOG_LOG, "Client %s native query: %s (%s)",
1565 client_get_id(cl), cl->cqlquery, sru);
1568 odr_destroy(odr_out);
1570 /* TODO FIX Not thread safe */
1573 // Initialize relevance structure with query terms
1574 se->relevance = relevance_create_ccl(se->service->charsets, cn,
1575 se->service->rank_cluster,
1576 se->service->rank_follow,
1577 se->service->rank_lead,
1578 se->service->rank_length);
1584 int client_parse_sort(struct client *cl, struct reclist_sortparms *sp)
1588 const char *sort_strategy_and_spec =
1589 get_strategy_plus_sort(cl, sp->name);
1590 int increasing = sp->increasing;
1591 if (!strcmp(sp->name, "relevance"))
1593 if (sort_strategy_and_spec && strlen(sort_strategy_and_spec) < 40)
1595 char strategy[50], *p;
1596 strcpy(strategy, sort_strategy_and_spec);
1597 p = strchr(strategy, ':');
1600 // Split the string in two
1608 yaz_log(YLOG_LOG, "Client %s: "
1609 "applying sorting %s %s", client_get_id(cl),
1611 if (!cl->sort_strategy || strcmp(cl->sort_strategy, strategy))
1612 cl->same_search = 0;
1613 if (!cl->sort_criteria || strcmp(cl->sort_criteria, p))
1614 cl->same_search = 0;
1615 if (cl->same_search == 0) {
1616 xfree(cl->sort_strategy);
1617 cl->sort_strategy = xstrdup(strategy);
1618 xfree(cl->sort_criteria);
1619 cl->sort_criteria = xstrdup(p);
1623 yaz_log(YLOG_LOG, "Client %s: "
1624 "Invalid sort strategy and spec found %s",
1625 client_get_id(cl), sort_strategy_and_spec);
1626 xfree(cl->sort_strategy);
1627 cl->sort_strategy = 0;
1628 xfree(cl->sort_criteria);
1629 cl->sort_criteria = 0;
1634 yaz_log(YLOG_DEBUG, "Client %s: "
1635 "No sort strategy and spec found.", client_get_id(cl));
1636 xfree(cl->sort_strategy);
1637 cl->sort_strategy = 0;
1638 xfree(cl->sort_criteria);
1639 cl->sort_criteria = 0;
1643 return !cl->same_search;
1646 void client_set_session(struct client *cl, struct session *se)
1651 int client_is_active(struct client *cl)
1653 if (cl->connection && (cl->state == Client_Connecting ||
1654 cl->state == Client_Working))
1659 int client_is_active_preferred(struct client *cl)
1661 /* only count if this is a preferred target. */
1664 /* TODO No sure this the condition that Seb wants */
1665 if (cl->connection && (cl->state == Client_Connecting ||
1666 cl->state == Client_Working))
1671 Odr_int client_get_hits(struct client *cl)
1676 Odr_int client_get_approximation(struct client *cl)
1678 if (cl->record_offset > 0)
1680 Odr_int approx = ((10 * cl->hits * (cl->record_offset - cl->filtered))
1681 / cl->record_offset + 5) /10;
1682 yaz_log(YLOG_DEBUG, "%s: Approx: %lld * %d / %d = %lld ",
1683 client_get_id(cl), cl->hits,
1684 cl->record_offset - cl->filtered, cl->record_offset, approx);
1690 int client_get_num_records(struct client *cl, int *filtered, int *ingest,
1694 *filtered = cl->filtered;
1696 *ingest = cl->ingest_failures;
1698 *failed = cl->record_failures;
1699 return cl->record_offset;
1702 void client_set_diagnostic(struct client *cl, int diagnostic,
1703 const char *message, const char *addinfo)
1705 cl->diagnostic = diagnostic;
1707 cl->message = xstrdup(message);
1711 cl->addinfo = xstrdup(addinfo);
1714 int client_get_diagnostic(struct client *cl, const char **message,
1715 const char **addinfo)
1718 *message = cl->message;
1720 *addinfo = cl->addinfo;
1721 return cl->diagnostic;
1724 const char * client_get_suggestions_xml(struct client *cl, WRBUF wrbuf)
1727 struct suggestions *suggestions = cl->suggestions;
1731 if (suggestions->passthrough)
1733 yaz_log(YLOG_DEBUG, "Passthrough Suggestions: \n%s\n",
1734 suggestions->passthrough);
1735 return suggestions->passthrough;
1737 if (suggestions->num == 0)
1740 for (idx = 0; idx < suggestions->num; idx++) {
1741 wrbuf_printf(wrbuf, "<suggest term=\"%s\"", suggestions->suggest[idx]);
1742 if (suggestions->misspelled[idx] && suggestions->misspelled[idx]) {
1743 wrbuf_puts(wrbuf, suggestions->misspelled[idx]);
1744 wrbuf_puts(wrbuf, "</suggest>\n");
1747 wrbuf_puts(wrbuf, "/>\n");
1750 return wrbuf_cstr(wrbuf);
1754 void client_set_database(struct client *cl, struct session_database *db)
1759 const char *client_get_id(struct client *cl)
1764 int client_get_maxrecs(struct client *cl)
1769 void client_set_preferred(struct client *cl, int v)
1775 struct suggestions* client_suggestions_create(const char* suggestions_string)
1779 struct suggestions *suggestions;
1780 if (suggestions_string == 0 || suggestions_string[0] == 0 )
1782 nmem = nmem_create();
1783 suggestions = nmem_malloc(nmem, sizeof(*suggestions));
1784 yaz_log(YLOG_DEBUG, "client target suggestions: %s.", suggestions_string);
1786 suggestions->nmem = nmem;
1787 suggestions->num = 0;
1788 suggestions->misspelled = 0;
1789 suggestions->suggest = 0;
1790 suggestions->passthrough = nmem_strdup_null(nmem, suggestions_string);
1792 if (suggestions_string)
1793 nmem_strsplit_escape2(suggestions->nmem, "\n", suggestions_string, &suggestions->suggest,
1794 &suggestions->num, 1, '\\', 0);
1795 /* Set up misspelled array */
1796 suggestions->misspelled = (char **)
1797 nmem_malloc(nmem, suggestions->num * sizeof(*suggestions->misspelled));
1798 /* replace = with \0 .. for each item */
1799 for (i = 0; i < suggestions->num; i++)
1801 char *cp = strchr(suggestions->suggest[i], '=');
1804 suggestions->misspelled[i] = cp+1;
1810 static void client_suggestions_destroy(struct client *cl)
1812 NMEM nmem = cl->suggestions->nmem;
1813 cl->suggestions = 0;
1820 * c-file-style: "Stroustrup"
1821 * indent-tabs-mode: nil
1823 * vim: shiftwidth=4 tabstop=8 expandtab