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
21 \brief high-level logic; mostly user sessions and settings
46 #include <yaz/marcdisp.h>
47 #include <yaz/comstack.h>
48 #include <yaz/tcpip.h>
49 #include <yaz/proto.h>
50 #include <yaz/readconf.h>
51 #include <yaz/pquery.h>
52 #include <yaz/otherinfo.h>
53 #include <yaz/yaz-util.h>
55 #include <yaz/query-charset.h>
56 #include <yaz/querytowrbuf.h>
57 #include <yaz/oid_db.h>
58 #include <yaz/snprintf.h>
59 #include <yaz/xml_get.h>
63 #include <yaz/timing.h>
67 #include "parameters.h"
71 #include "termlists.h"
73 #include "relevance.h"
77 #include "normalize7bit.h"
79 #include <libxml/tree.h>
83 #define MAX(a,b) ((a)>(b)?(a):(b))
85 // Note: Some things in this structure will eventually move to configuration
86 struct parameters global_parameters =
90 0, // predictable sessions
94 struct client *client;
95 struct client_list *next;
98 /* session counting (1) , disable client counting (0) */
99 static YAZ_MUTEX g_session_mutex = 0;
100 static int no_sessions = 0;
102 static int session_use(int delta)
105 if (!g_session_mutex)
106 yaz_mutex_create(&g_session_mutex);
107 yaz_mutex_enter(g_session_mutex);
108 no_sessions += delta;
109 sessions = no_sessions;
110 yaz_mutex_leave(g_session_mutex);
111 yaz_log(YLOG_DEBUG, "%s sessions=%d", delta == 0 ? "" :
112 (delta > 0 ? "INC" : "DEC"), no_sessions);
116 int sessions_count(void)
118 return session_use(0);
121 static void log_xml_doc(xmlDoc *doc)
123 FILE *lf = yaz_log_file();
126 #if LIBXML_VERSION >= 20600
127 xmlDocDumpFormatMemory(doc, &result, &len, 1);
129 xmlDocDumpMemory(doc, &result, &len);
133 (void) fwrite(result, 1, len, lf);
139 static void session_enter(struct session *s, const char *caller)
142 session_log(s, YLOG_DEBUG, "Session lock by %s", caller);
143 yaz_mutex_enter(s->session_mutex);
146 static void session_leave(struct session *s, const char *caller)
148 yaz_mutex_leave(s->session_mutex);
150 session_log(s, YLOG_DEBUG, "Session unlock by %s", caller);
153 static int run_icu(struct session *s, const char *icu_chain_id,
155 WRBUF norm_wr, WRBUF disp_wr)
157 const char *facet_component;
158 struct conf_service *service = s->service;
159 pp2_charset_token_t prt =
160 pp2_charset_token_create(service->charsets, icu_chain_id);
163 session_log(s, YLOG_FATAL,
164 "Unknown ICU chain '%s'", icu_chain_id);
167 pp2_charset_token_first(prt, value, 0);
168 while ((facet_component = pp2_charset_token_next(prt)))
170 const char *display_component;
171 if (*facet_component)
173 if (wrbuf_len(norm_wr))
174 wrbuf_puts(norm_wr, " ");
175 wrbuf_puts(norm_wr, facet_component);
177 display_component = pp2_get_display(prt);
178 if (display_component)
180 if (wrbuf_len(disp_wr))
181 wrbuf_puts(disp_wr, " ");
182 wrbuf_puts(disp_wr, display_component);
185 pp2_charset_token_destroy(prt);
189 static void session_normalize_facet(struct session *s,
190 const char *type, const char *value,
191 WRBUF display_wrbuf, WRBUF facet_wrbuf)
193 struct conf_service *service = s->service;
195 const char *icu_chain_id = 0;
197 for (i = 0; i < service->num_metadata; i++)
198 if (!strcmp((service->metadata + i)->name, type))
199 icu_chain_id = (service->metadata + i)->facetrule;
201 icu_chain_id = "facet";
203 run_icu(s, icu_chain_id, value, facet_wrbuf, display_wrbuf);
211 struct facet_id *next;
214 static void session_add_id_facet(struct session *s, struct client *cl,
220 struct facet_id *t = nmem_malloc(s->session_nmem, sizeof(*t));
222 t->client_id = nmem_strdup(s->session_nmem, client_get_id(cl));
223 t->type = nmem_strdup(s->session_nmem, type);
224 t->id = nmem_strdupn(s->session_nmem, id, id_len);
225 t->term = nmem_strdup(s->session_nmem, term);
226 t->next = s->facet_id_list;
227 s->facet_id_list = t;
231 // Look up a facet term, and return matching id
232 // If facet type not found, returns 0
233 // If facet type found, but no matching term, returns ""
234 const char *session_lookup_id_facet(struct session *s, struct client *cl,
239 struct facet_id *t = s->facet_id_list;
240 for (; t; t = t->next)
242 if (!strcmp(client_get_id(cl), t->client_id) && !strcmp(t->type, type) )
245 if ( !strcmp(t->term, term))
254 void add_facet(struct session *s, const char *type, const char *value, int count, struct client *cl)
256 WRBUF facet_wrbuf = wrbuf_alloc();
257 WRBUF display_wrbuf = wrbuf_alloc();
261 /* inspect pz:facetmap:split:name ?? */
262 if (!strncmp(type, "split:", 6))
264 const char *cp = strchr(value, ':');
274 session_normalize_facet(s, type, value, display_wrbuf, facet_wrbuf);
275 if (wrbuf_len(facet_wrbuf))
277 struct named_termlist **tp = &s->termlists;
278 for (; (*tp); tp = &(*tp)->next)
279 if (!strcmp((*tp)->name, type))
283 *tp = nmem_malloc(s->nmem, sizeof(**tp));
284 (*tp)->name = nmem_strdup(s->nmem, type);
285 (*tp)->termlist = termlist_create(s->nmem);
288 termlist_insert((*tp)->termlist, wrbuf_cstr(display_wrbuf),
289 wrbuf_cstr(facet_wrbuf), id, id_len, count);
291 session_add_id_facet(s, cl, type, id, id_len,
292 wrbuf_cstr(display_wrbuf));
294 wrbuf_destroy(facet_wrbuf);
295 wrbuf_destroy(display_wrbuf);
298 static xmlDoc *record_to_xml(struct session *se,
299 struct session_database *sdb, const char *rec)
301 struct database *db = sdb->database;
304 rdoc = xmlParseMemory(rec, strlen(rec));
308 session_log(se, YLOG_WARN, "Non-wellformed XML");
312 if (global_parameters.dump_records)
314 session_log(se, YLOG_LOG, "Un-normalized record from %s", db->id);
321 #define MAX_XSLT_ARGS 16
323 // Add static values from session database settings if applicable
324 static void insert_settings_parameters(struct session_database *sdb,
325 struct conf_service *service,
333 for (i = 0; i < service->num_metadata; i++)
335 struct conf_metadata *md = &service->metadata[i];
338 if (md->setting == Metadata_setting_parameter &&
339 (setting = settings_lookup_offset(service, md->name)) >= 0)
341 const char *val = session_setting_oneval(sdb, setting);
342 if (val && nparms < MAX_XSLT_ARGS)
345 int len = strlen(val);
346 buf = nmem_malloc(nmem, len + 3);
348 strcpy(buf + 1, val);
351 parms[offset++] = md->name;
352 parms[offset++] = buf;
360 // Add static values from session database settings if applicable
361 static void insert_settings_values(struct session_database *sdb, xmlDoc *doc,
363 struct conf_service *service)
367 for (i = 0; i < service->num_metadata; i++)
369 struct conf_metadata *md = &service->metadata[i];
372 if (md->setting == Metadata_setting_postproc &&
373 (offset = settings_lookup_offset(service, md->name)) >= 0)
375 const char *val = session_setting_oneval(sdb, offset);
378 xmlNode *n = xmlNewTextChild(root, 0, (xmlChar *) "metadata",
380 xmlSetProp(n, (xmlChar *) "type", (xmlChar *) md->name);
386 static xmlDoc *normalize_record(struct session *se,
387 struct session_database *sdb,
388 struct conf_service *service,
389 const char *rec, NMEM nmem)
391 xmlDoc *rdoc = record_to_xml(se, sdb, rec);
395 char *parms[MAX_XSLT_ARGS*2+1];
397 insert_settings_parameters(sdb, service, parms, nmem);
399 if (normalize_record_transform(sdb->map, &rdoc, (const char **)parms))
401 session_log(se, YLOG_WARN, "Normalize failed");
407 void session_settings_dump(struct session *se,
408 struct session_database *db,
413 int i, num = db->num_settings;
414 for (i = 0; i < num; i++)
416 struct setting *s = db->settings[i];
417 for (;s ; s = s->next)
419 wrbuf_puts(w, "<set name=\"");
420 wrbuf_xmlputs(w, s->name);
421 wrbuf_puts(w, "\" value=\"");
422 wrbuf_xmlputs(w, s->value);
423 wrbuf_puts(w, "\"/>");
431 // Retrieve first defined value for 'name' for given database.
432 // Will be extended to take into account user associated with session
433 const char *session_setting_oneval(struct session_database *db, int offset)
435 if (offset >= db->num_settings || !db->settings[offset])
437 return db->settings[offset]->value;
440 // Prepare XSLT stylesheets for record normalization
441 // Structures are allocated on the session_wide nmem to avoid having
442 // to recompute this for every search. This would lead
443 // to leaking if a single session was to repeatedly change the PZ_XSLT
444 // setting. However, this is not a realistic use scenario.
445 static int prepare_map(struct session *se, struct session_database *sdb)
447 if (sdb->settings && !sdb->map)
451 if (sdb->settings[PZ_XSLT] &&
452 (s = session_setting_oneval(sdb, PZ_XSLT)))
454 char auto_stylesheet[256];
456 if (!strcmp(s, "auto"))
458 const char *request_syntax = session_setting_oneval(
459 sdb, PZ_REQUESTSYNTAX);
463 yaz_snprintf(auto_stylesheet, sizeof(auto_stylesheet),
464 "%s.xsl", request_syntax);
465 for (cp = auto_stylesheet; *cp; cp++)
467 /* deliberately only consider ASCII */
468 if (*cp > 32 && *cp < 127)
475 session_log(se, YLOG_WARN,
476 "No pz:requestsyntax for auto stylesheet");
479 sdb->map = normalize_cache_get(se->normalize_cache,
488 // called if watch should be removed because http_channel is to be destroyed
489 static void session_watch_cancel(void *data, struct http_channel *c,
492 struct session_watchentry *ent = data;
499 // set watch. Returns 0=OK, -1 if watch is already set
500 int session_set_watch(struct session *s, int what,
501 session_watchfun fun, void *data,
502 struct http_channel *chan)
505 session_enter(s, "session_set_watch");
506 if (s->watchlist[what].fun)
511 s->watchlist[what].fun = fun;
512 s->watchlist[what].data = data;
513 s->watchlist[what].obs = http_add_observer(chan, &s->watchlist[what],
514 session_watch_cancel);
517 session_leave(s, "session_set_watch");
521 void session_alert_watch(struct session *s, int what)
524 session_enter(s, "session_alert_watch");
525 if (s->watchlist[what].fun)
527 /* our watch is no longer associated with http_channel */
529 session_watchfun fun;
531 http_remove_observer(s->watchlist[what].obs);
532 fun = s->watchlist[what].fun;
533 data = s->watchlist[what].data;
535 /* reset watch before fun is invoked - in case fun wants to set
537 s->watchlist[what].fun = 0;
538 s->watchlist[what].data = 0;
539 s->watchlist[what].obs = 0;
541 session_leave(s, "session_alert_watch");
542 session_log(s, YLOG_DEBUG,
543 "Alert Watch: %d calling function: %p", what, fun);
547 session_leave(s,"session_alert_watch");
550 //callback for grep_databases
551 static void select_targets_callback(struct session *se,
552 struct session_database *db)
555 struct client_list *l;
557 for (l = se->clients_cached; l; l = l->next)
558 if (client_get_database(l->client) == db)
565 cl = client_create(db->database->id);
566 client_set_database(cl, db);
568 l = xmalloc(sizeof(*l));
570 l->next = se->clients_cached;
571 se->clients_cached = l;
573 client_set_session(cl, se);
575 l = xmalloc(sizeof(*l));
577 l->next = se->clients_active;
578 se->clients_active = l;
581 static void session_reset_active_clients(struct session *se,
582 struct client_list *new_list)
584 struct client_list *l;
586 session_enter(se, "session_reset_active_clients");
587 l = se->clients_active;
588 se->clients_active = new_list;
589 session_leave(se, "session_reset_active_clients");
593 struct client_list *l_next = l->next;
595 client_lock(l->client);
596 client_set_session(l->client, 0); /* mark client inactive */
597 client_unlock(l->client);
604 static void session_remove_cached_clients(struct session *se)
606 struct client_list *l;
608 session_reset_active_clients(se, 0);
610 session_enter(se, "session_remove_cached_clients");
611 l = se->clients_cached;
612 se->clients_cached = 0;
613 session_leave(se, "session_remove_cached_clients");
617 struct client_list *l_next = l->next;
618 client_lock(l->client);
619 client_set_session(l->client, 0);
620 client_set_database(l->client, 0);
621 client_mark_dead(l->client);
622 client_unlock(l->client);
623 client_destroy(l->client);
629 // Associates a set of clients with a session;
630 // Note: Session-databases represent databases with per-session
632 static int select_targets(struct session *se, const char *filter)
634 return session_grep_databases(se, filter, select_targets_callback);
637 int session_active_clients(struct session *s)
639 struct client_list *l;
642 for (l = s->clients_active; l; l = l->next)
643 if (client_is_active(l->client))
649 int session_is_preferred_clients_ready(struct session *s)
651 struct client_list *l;
654 for (l = s->clients_active; l; l = l->next)
655 if (client_is_active_preferred(l->client))
657 session_log(s, YLOG_DEBUG, "Has %d active preferred clients.", res);
661 static void session_clear_set(struct session *se, struct reclist_sortparms *sp)
663 reclist_destroy(se->reclist);
664 if (nmem_total(se->nmem))
665 session_log(se, YLOG_DEBUG, "NMEN operation usage %zd",
666 nmem_total(se->nmem));
667 nmem_reset(se->nmem);
668 se->total_records = se->total_merged = 0;
670 relevance_clear(se->relevance);
672 /* reset list of sorted results and clear to relevance search */
673 se->sorted_results = nmem_malloc(se->nmem, sizeof(*se->sorted_results));
674 se->sorted_results->name = nmem_strdup(se->nmem, sp->name);
675 se->sorted_results->increasing = sp->increasing;
676 se->sorted_results->type = sp->type;
677 se->sorted_results->next = 0;
679 session_log(se, YLOG_DEBUG, "clear_set session_sort: field=%s increasing=%d type=%d configured",
680 sp->name, sp->increasing, sp->type);
682 se->reclist = reclist_create(se->nmem);
685 void session_sort(struct session *se, struct reclist_sortparms *sp,
686 const char *mergekey, const char *rank)
688 struct client_list *l;
689 const char *field = sp->name;
690 int increasing = sp->increasing;
692 int clients_research = 0;
694 session_enter(se, "session_sort");
695 session_log(se, YLOG_DEBUG, "session_sort field=%s increasing=%d type=%d",
696 field, increasing, type);
698 if (rank && (!se->rank || strcmp(se->rank, rank)))
700 /* new rank must research/reingest anyway */
703 se->rank = *rank ? xstrdup(rank) : 0;
704 clients_research = 1;
705 session_log(se, YLOG_DEBUG, "session_sort: new rank = %s",
708 if (mergekey && (!se->mergekey || strcmp(se->mergekey, mergekey)))
710 /* new mergekey must research/reingest anyway */
713 se->mergekey = *mergekey ? xstrdup(mergekey) : 0;
714 clients_research = 1;
715 session_log(se, YLOG_DEBUG, "session_sort: new mergekey = %s",
718 if (clients_research == 0)
720 struct reclist_sortparms *sr;
721 for (sr = se->sorted_results; sr; sr = sr->next)
722 if (!reclist_sortparms_cmp(sr, sp))
726 session_log(se, YLOG_LOG, "session_sort: field=%s increasing=%d type=%d already fetched",
727 field, increasing, type);
728 session_leave(se, "session_sort");
732 session_log(se, YLOG_DEBUG, "session_sort: field=%s increasing=%d type=%d must fetch",
733 field, increasing, type);
735 // We need to reset reclist on every sort that changes the records, not just for position
736 // So if just one client requires new searching, we need to clear set.
737 // Ask each of the client if sorting requires re-search due to native sort
738 // If it does it will require us to
739 for (l = se->clients_active; l; l = l->next)
741 struct client *cl = l->client;
742 // Assume no re-search is required.
743 client_parse_init(cl, 1);
744 clients_research += client_parse_sort(cl, sp, 0);
746 if (!clients_research || se->clients_starting)
748 // A new sorting based on same record set
749 struct reclist_sortparms *sr = nmem_malloc(se->nmem, sizeof(*sr));
750 sr->name = nmem_strdup(se->nmem, field);
751 sr->increasing = increasing;
753 sr->next = se->sorted_results;
754 se->sorted_results = sr;
755 session_log(se, YLOG_DEBUG, "session_sort: no research/ingesting done");
756 session_leave(se, "session_sort");
760 se->clients_starting = 1;
761 session_log(se, YLOG_DEBUG,
762 "session_sort: reset results due to %d clients researching",
764 session_clear_set(se, sp);
765 session_log(se, YLOG_DEBUG, "Re- search/ingesting for clients due to change in sort order");
767 session_leave(se, "session_sort");
768 for (l = se->clients_active; l; l = l->next)
770 struct client *cl = l->client;
771 if (client_get_state(cl) == Client_Connecting ||
772 client_get_state(cl) == Client_Idle ||
773 client_get_state(cl) == Client_Working) {
774 client_start_search(cl);
778 session_log(se, YLOG_DEBUG,
779 "session_sort: %s: No re-start/ingest in show. "
780 "Wrong client state: %d",
781 client_get_id(cl), client_get_state(cl));
784 session_enter(se, "session_sort");
785 se->clients_starting = 0;
786 se->force_position = 0;
787 session_leave(se, "session_sort");
791 void session_stop(struct session *se)
793 struct client_list *l;
794 session_enter(se, "session_stop1");
795 if (se->clients_starting)
797 session_leave(se, "session_stop1");
800 se->clients_starting = 1;
801 session_leave(se, "session_stop1");
803 session_alert_watch(se, SESSION_WATCH_SHOW);
804 session_alert_watch(se, SESSION_WATCH_BYTARGET);
805 session_alert_watch(se, SESSION_WATCH_TERMLIST);
806 session_alert_watch(se, SESSION_WATCH_SHOW_PREF);
808 for (l = se->clients_active; l; l = l->next)
810 struct client *cl = l->client;
813 session_enter(se, "session_stop2");
814 se->clients_starting = 0;
815 session_leave(se, "session_stop2");
818 enum pazpar2_error_code session_search(struct session *se,
820 const char *startrecs,
824 const char **addinfo,
825 const char **addinfo2,
826 struct reclist_sortparms *sp,
827 const char *mergekey,
830 int live_channels = 0;
832 int no_failed_query = 0;
833 int no_failed_limit = 0;
835 struct client_list *l;
837 session_log(se, YLOG_DEBUG, "Search");
841 session_enter(se, "session_search0");
842 if (se->clients_starting)
844 session_leave(se, "session_search0");
845 return PAZPAR2_NO_ERROR;
847 se->clients_starting = 1;
848 se->force_position = 0;
849 session_leave(se, "session_search0");
851 if (se->settings_modified) {
852 session_remove_cached_clients(se);
855 session_reset_active_clients(se, 0);
857 session_enter(se, "session_search");
858 se->settings_modified = 0;
863 se->mergekey = *mergekey ? xstrdup(mergekey) : 0;
868 se->rank = *rank ? xstrdup(rank) : 0;
871 session_clear_set(se, sp);
872 relevance_destroy(&se->relevance);
874 live_channels = select_targets(se, filter);
877 session_leave(se, "session_search");
878 se->clients_starting = 0;
879 return PAZPAR2_NO_TARGETS;
882 facet_limits_destroy(se->facet_limits);
883 se->facet_limits = facet_limits_create(limit);
884 if (!se->facet_limits)
887 session_leave(se, "session_search");
888 se->clients_starting = 0;
889 session_reset_active_clients(se, 0);
890 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
893 session_leave(se, "session_search");
895 session_alert_watch(se, SESSION_WATCH_SHOW);
896 session_alert_watch(se, SESSION_WATCH_BYTARGET);
897 session_alert_watch(se, SESSION_WATCH_TERMLIST);
898 session_alert_watch(se, SESSION_WATCH_SHOW_PREF);
900 for (l = se->clients_active; l; l = l->next)
903 struct client *cl = l->client;
904 client_parse_init(cl, 1);
905 if (prepare_map(se, client_get_database(cl)) < 0)
908 parse_ret = client_parse_query(cl, query, se->facet_limits, addinfo2);
911 else if (parse_ret == -2)
913 else if (parse_ret < 0)
914 no_working++; /* other error, such as bad CCL map */
917 client_parse_range(cl, startrecs, maxrecs);
918 client_parse_sort(cl, sp, &no_sortmap);
919 client_start_search(cl);
923 yaz_log(YLOG_LOG, "session_search: no_working=%d no_sortmap=%d",
924 no_working, no_sortmap);
925 session_enter(se, "session_search2");
926 if (no_working == 1 && no_sortmap == 1)
928 se->force_position = 1;
929 yaz_log(YLOG_LOG, "force_position=1");
931 se->clients_starting = 0;
932 session_leave(se, "session_search2");
935 if (no_failed_query > 0)
938 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
940 else if (no_failed_limit > 0)
943 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
946 return PAZPAR2_NO_TARGETS;
948 return PAZPAR2_NO_ERROR;
951 // Creates a new session_database object for a database
952 static void session_init_databases_fun(void *context, struct database *db)
954 struct session *se = (struct session *) context;
955 struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
961 assert(db->settings);
962 new->settings = nmem_malloc(se->session_nmem,
963 sizeof(struct settings *) * db->num_settings);
964 new->num_settings = db->num_settings;
965 for (i = 0; i < db->num_settings; i++)
967 struct setting *setting = db->settings[i];
968 new->settings[i] = setting;
970 new->next = se->databases;
974 // Doesn't free memory associated with sdb -- nmem takes care of that
975 static void session_database_destroy(struct session_database *sdb)
980 // Initialize session_database list -- this represents this session's view
981 // of the database list -- subject to modification by the settings ws command
982 void session_init_databases(struct session *se)
985 predef_grep_databases(se, se->service, session_init_databases_fun);
988 // Probably session_init_databases_fun should be refactored instead of
990 static struct session_database *load_session_database(struct session *se,
993 struct database *db = new_database_inherit_settings(id, se->session_nmem, se->service->settings);
994 session_init_databases_fun((void*) se, db);
996 // New sdb is head of se->databases list
997 return se->databases;
1000 // Find an existing session database. If not found, load it
1001 static struct session_database *find_session_database(struct session *se,
1004 struct session_database *sdb;
1006 for (sdb = se->databases; sdb; sdb = sdb->next)
1007 if (!strcmp(sdb->database->id, id))
1009 return load_session_database(se, id);
1012 // Apply a session override to a database
1013 void session_apply_setting(struct session *se, const char *dbname,
1014 const char *name, const char *value)
1016 session_enter(se, "session_apply_setting");
1018 struct session_database *sdb = find_session_database(se, dbname);
1019 struct conf_service *service = se->service;
1021 int offset = settings_create_offset(service, name);
1023 expand_settings_array(&sdb->settings, &sdb->num_settings, offset,
1025 // Force later recompute of settings-driven data structures
1026 // (happens when a search starts and client connections are prepared)
1027 if (offset == PZ_XSLT)
1029 se->settings_modified = 1;
1030 for (s = sdb->settings[offset]; s; s = s->next)
1031 if (!strcmp(s->name, name) &&
1032 dbname && s->target && !strcmp(dbname, s->target))
1036 s = nmem_malloc(se->session_nmem, sizeof(*s));
1038 s->target = nmem_strdup(se->session_nmem, dbname);
1039 s->name = nmem_strdup(se->session_nmem, name);
1040 s->next = sdb->settings[offset];
1041 sdb->settings[offset] = s;
1043 s->value = nmem_strdup(se->session_nmem, value);
1045 session_leave(se, "session_apply_setting");
1048 void session_destroy(struct session *se)
1050 struct session_database *sdb;
1051 int i = session_use(-1);
1053 session_log(se, YLOG_LOG, "destroy "
1054 "session-total %d nmem-op %zd nmem-ses %zd", i,
1055 nmem_total(se->nmem), nmem_total(se->session_nmem));
1056 session_remove_cached_clients(se);
1058 for (sdb = se->databases; sdb; sdb = sdb->next)
1059 session_database_destroy(sdb);
1060 normalize_cache_destroy(se->normalize_cache);
1061 relevance_destroy(&se->relevance);
1062 reclist_destroy(se->reclist);
1063 xfree(se->mergekey);
1065 facet_limits_destroy(se->facet_limits);
1066 nmem_destroy(se->nmem);
1067 service_destroy(se->service);
1068 yaz_mutex_destroy(&se->session_mutex);
1071 size_t session_get_memory_status(struct session *session) {
1072 size_t session_nmem;
1075 session_enter(session, "session_get_memory_status");
1076 session_nmem = nmem_total(session->nmem);
1077 session_leave(session, "session_get_memory_status");
1078 return session_nmem;
1082 struct session *new_session(NMEM nmem, struct conf_service *service,
1083 unsigned session_id)
1086 struct session *session = nmem_malloc(nmem, sizeof(*session));
1090 sprintf(tmp_str, "session#%u", session_id);
1092 session->session_id = session_id;
1093 session_log(session, YLOG_DEBUG, "New");
1094 session->service = service;
1095 session->relevance = 0;
1096 session->total_records = 0;
1097 session->number_of_warnings_unknown_elements = 0;
1098 session->number_of_warnings_unknown_metadata = 0;
1099 session->termlists = 0;
1100 session->reclist = reclist_create(nmem);
1101 session->clients_active = 0;
1102 session->clients_cached = 0;
1103 session->settings_modified = 0;
1104 session->session_nmem = nmem;
1105 session->facet_id_list = 0;
1106 session->nmem = nmem_create();
1107 session->databases = 0;
1108 session->sorted_results = 0;
1109 session->facet_limits = 0;
1110 session->mergekey = 0;
1112 session->clients_starting = 0;
1113 session->force_position = 0;
1115 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1117 session->watchlist[i].data = 0;
1118 session->watchlist[i].fun = 0;
1120 session->normalize_cache = normalize_cache_create();
1121 session->session_mutex = 0;
1122 pazpar2_mutex_create(&session->session_mutex, tmp_str);
1125 session_log(session, YLOG_LOG, "create session-total %d", i);
1129 static struct hitsbytarget *hitsbytarget_nb(struct session *se,
1130 int *count, NMEM nmem)
1132 struct hitsbytarget *res = 0;
1133 struct client_list *l;
1136 for (l = se->clients_active; l; l = l->next)
1139 res = nmem_malloc(nmem, sizeof(*res) * sz);
1141 for (l = se->clients_active; l; l = l->next)
1143 struct client *cl = l->client;
1144 WRBUF w = wrbuf_alloc();
1145 const char *name = session_setting_oneval(client_get_database(cl),
1147 res[*count].id = client_get_id(cl);
1148 res[*count].name = *name ? name : "Unknown";
1149 res[*count].hits = client_get_hits(cl);
1150 res[*count].approximation = client_get_approximation(cl);
1151 res[*count].records = client_get_num_records(cl,
1152 &res[*count].filtered,
1154 res[*count].diagnostic =
1155 client_get_diagnostic(cl, &res[*count].message,
1156 &res[*count].addinfo);
1157 res[*count].state = client_get_state_str(cl);
1158 res[*count].connected = client_get_connection(cl) ? 1 : 0;
1159 session_settings_dump(se, client_get_database(cl), w);
1160 res[*count].settings_xml = nmem_strdup(nmem, wrbuf_cstr(w));
1162 res[*count].suggestions_xml =
1163 nmem_strdup(nmem, client_get_suggestions_xml(cl, w));
1165 res[*count].query_data =
1166 client_get_query(cl, &res[*count].query_type, nmem);
1173 struct hitsbytarget *get_hitsbytarget(struct session *se, int *count, NMEM nmem)
1175 struct hitsbytarget *p;
1176 session_enter(se, "get_hitsbytarget");
1177 p = hitsbytarget_nb(se, count, nmem);
1178 session_leave(se, "get_hitsbytarget");
1182 // Compares two hitsbytarget nodes by hitcount
1183 static int cmp_ht(const void *p1, const void *p2)
1185 const struct hitsbytarget *h1 = p1;
1186 const struct hitsbytarget *h2 = p2;
1187 return h2->hits - h1->hits;
1190 // Compares two hitsbytarget nodes by hitcount
1191 static int cmp_ht_approx(const void *p1, const void *p2)
1193 const struct hitsbytarget *h1 = p1;
1194 const struct hitsbytarget *h2 = p2;
1195 return h2->approximation - h1->approximation;
1198 static int targets_termlist_nb(WRBUF wrbuf, struct session *se, int num,
1199 NMEM nmem, int version)
1201 struct hitsbytarget *ht;
1204 ht = hitsbytarget_nb(se, &count, nmem);
1206 qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht_approx);
1208 qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht);
1209 for (i = 0; i < count && i < num && ht[i].hits > 0; i++)
1212 // do only print terms which have display names
1214 wrbuf_puts(wrbuf, "<term>\n");
1216 wrbuf_puts(wrbuf, "<id>");
1217 wrbuf_xmlputs(wrbuf, ht[i].id);
1218 wrbuf_puts(wrbuf, "</id>\n");
1220 wrbuf_puts(wrbuf, "<name>");
1221 if (!ht[i].name || !ht[i].name[0])
1222 wrbuf_xmlputs(wrbuf, "NO TARGET NAME");
1224 wrbuf_xmlputs(wrbuf, ht[i].name);
1225 wrbuf_puts(wrbuf, "</name>\n");
1227 wrbuf_printf(wrbuf, "<frequency>" ODR_INT_PRINTF "</frequency>\n",
1231 // Should not print if we know it isn't a approximation.
1232 wrbuf_printf(wrbuf, "<approximation>" ODR_INT_PRINTF "</approximation>\n", ht[i].approximation);
1233 wrbuf_printf(wrbuf, "<records>%d</records>\n", ht[i].records - ht[i].filtered);
1234 wrbuf_printf(wrbuf, "<filtered>%d</filtered>\n", ht[i].filtered);
1237 wrbuf_puts(wrbuf, "<state>");
1238 wrbuf_xmlputs(wrbuf, ht[i].state);
1239 wrbuf_puts(wrbuf, "</state>\n");
1241 wrbuf_printf(wrbuf, "<diagnostic>%d</diagnostic>\n",
1243 wrbuf_puts(wrbuf, "</term>\n");
1248 void perform_termlist(struct http_channel *c, struct session *se,
1249 const char *name, int num, int version)
1252 NMEM nmem_tmp = nmem_create();
1259 nmem_strsplit(nmem_tmp, ",", name, &names, &num_names);
1261 session_enter(se, "perform_termlist");
1263 for (j = 0; j < num_names; j++)
1266 int must_generate_empty = 1; /* bug 5350 */
1268 struct named_termlist *t = se->termlists;
1269 for (; t; t = t->next)
1272 if (!strcmp(names[j], tname) || !strcmp(names[j], "*"))
1274 struct termlist_score **p = 0;
1277 wrbuf_puts(c->wrbuf, "<list name=\"");
1278 wrbuf_xmlputs(c->wrbuf, tname);
1279 wrbuf_puts(c->wrbuf, "\">\n");
1280 must_generate_empty = 0;
1282 p = termlist_highscore(t->termlist, &len, nmem_tmp);
1286 for (i = 0; i < len && i < num; i++)
1288 // prevent sending empty term elements
1289 if (!p[i]->display_term || !p[i]->display_term[0])
1292 wrbuf_puts(c->wrbuf, "<term>");
1293 wrbuf_puts(c->wrbuf, "<name>");
1294 wrbuf_xmlputs(c->wrbuf, p[i]->display_term);
1295 wrbuf_puts(c->wrbuf, "</name>");
1296 wrbuf_printf(c->wrbuf,
1297 "<frequency>%d</frequency>",
1299 wrbuf_puts(c->wrbuf, "</term>\n");
1302 wrbuf_puts(c->wrbuf, "</list>\n");
1306 if (!strcmp(names[j], tname) || !strcmp(names[j], "*"))
1308 wrbuf_puts(c->wrbuf, "<list name=\"");
1309 wrbuf_xmlputs(c->wrbuf, tname);
1310 wrbuf_puts(c->wrbuf, "\">\n");
1312 targets_termlist_nb(c->wrbuf, se, num, c->nmem, version);
1313 wrbuf_puts(c->wrbuf, "</list>\n");
1314 must_generate_empty = 0;
1316 if (must_generate_empty)
1318 wrbuf_puts(c->wrbuf, "<list name=\"");
1319 wrbuf_xmlputs(c->wrbuf, names[j]);
1320 wrbuf_puts(c->wrbuf, "\"/>\n");
1323 session_leave(se, "perform_termlist");
1324 nmem_destroy(nmem_tmp);
1327 #ifdef MISSING_HEADERS
1328 void report_nmem_stats(void)
1330 size_t in_use, is_free;
1332 nmem_get_memory_in_use(&in_use);
1333 nmem_get_memory_free(&is_free);
1335 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1336 (long) in_use, (long) is_free);
1340 struct record_cluster *show_single_start(struct session *se, const char *id,
1341 struct record_cluster **prev_r,
1342 struct record_cluster **next_r)
1344 struct record_cluster *r = 0;
1346 session_enter(se, "show_single_start");
1349 reclist_limit(se->reclist, se, 1);
1351 reclist_enter(se->reclist);
1352 while ((r = reclist_read_record(se->reclist)))
1354 if (!strcmp(r->recid, id))
1356 *next_r = reclist_read_record(se->reclist);
1361 reclist_leave(se->reclist);
1363 session_leave(se, "show_single_start");
1367 void show_single_stop(struct session *se, struct record_cluster *rec)
1369 session_leave(se, "show_single_stop");
1373 int session_fetch_more(struct session *se)
1375 struct client_list *l;
1378 for (l = se->clients_active; l; l = l->next)
1380 struct client *cl = l->client;
1381 if (client_get_state(cl) == Client_Idle)
1383 if (client_fetch_more(cl))
1385 session_log(se, YLOG_LOG, "%s: more to fetch",
1392 int ingest_failures;
1393 int record_failures;
1394 int num = client_get_num_records(
1395 cl, &filtered, &ingest_failures, &record_failures);
1397 session_log(se, YLOG_LOG, "%s: hits=" ODR_INT_PRINTF
1398 " fetched=%d filtered=%d",
1400 client_get_hits(cl),
1402 if (ingest_failures || record_failures)
1404 session_log(se, YLOG_WARN, "%s:"
1405 " ingest failures=%d record failures=%d",
1407 ingest_failures, record_failures);
1413 session_log(se, YLOG_LOG, "%s: no fetch due to state=%s",
1414 client_get_id(cl), client_get_state_str(cl));
1421 struct record_cluster **show_range_start(struct session *se,
1422 struct reclist_sortparms *sp,
1423 int start, int *num, int *total,
1424 Odr_int *sumhits, Odr_int *approx_hits,
1425 void (*show_records_ready)(void *data),
1426 struct http_channel *chan)
1428 struct record_cluster **recs = 0;
1429 struct reclist_sortparms *spp;
1430 struct client_list *l;
1434 yaz_timing_t t = yaz_timing_create();
1436 session_enter(se, "show_range_start");
1440 reclist_limit(se->reclist, se, 0);
1443 for (spp = sp; spp; spp = spp->next)
1444 if (spp->type == Metadata_type_relevance)
1446 relevance_prepare_read(se->relevance, se->reclist);
1449 for (l = se->clients_active; l; l = l->next) {
1450 *sumhits += client_get_hits(l->client);
1451 *approx_hits += client_get_approximation(l->client);
1454 if (se->force_position)
1456 nmem_tmp = nmem_create();
1457 sp = reclist_parse_sortparms(nmem_tmp, "position:1", 0);
1460 reclist_sort(se->reclist, sp);
1462 nmem_destroy(nmem_tmp);
1464 reclist_enter(se->reclist);
1465 *total = reclist_get_num_records(se->reclist);
1467 for (l = se->clients_active; l; l = l->next)
1468 client_update_show_stat(l->client, 0);
1470 for (i = 0; i < start; i++)
1472 struct record_cluster *r = reclist_read_record(se->reclist);
1480 struct record *rec = r->records;
1481 for (;rec; rec = rec->next)
1482 client_update_show_stat(rec->client, 1);
1485 recs = nmem_malloc(se->nmem, (*num > 0 ? *num : 1) * sizeof(*recs));
1486 for (i = 0; i < *num; i++)
1488 struct record_cluster *r = reclist_read_record(se->reclist);
1496 struct record *rec = r->records;
1497 for (;rec; rec = rec->next)
1498 client_update_show_stat(rec->client, 1);
1502 reclist_leave(se->reclist);
1505 session_log(se, YLOG_LOG, "show %6.5f %3.2f %3.2f",
1506 yaz_timing_get_real(t), yaz_timing_get_user(t),
1507 yaz_timing_get_sys(t));
1508 yaz_timing_destroy(&t);
1511 if (!session_fetch_more(se))
1512 session_log(se, YLOG_LOG, "can not fetch more");
1515 show_range_stop(se, recs);
1516 session_log(se, YLOG_LOG, "fetching more in progress");
1517 if (session_set_watch(se, SESSION_WATCH_SHOW,
1518 show_records_ready, chan, chan))
1520 session_log(se, YLOG_WARN, "Ignoring show block");
1521 session_enter(se, "show_range_start");
1525 session_log(se, YLOG_LOG, "session watch OK");
1532 void show_range_stop(struct session *se, struct record_cluster **recs)
1534 session_leave(se, "show_range_stop");
1537 void statistics(struct session *se, struct statistics *stat)
1539 struct client_list *l;
1542 memset(stat, 0, sizeof(*stat));
1544 for (l = se->clients_active; l; l = l->next)
1546 struct client *cl = l->client;
1547 if (!client_get_connection(cl))
1548 stat->num_no_connection++;
1549 stat->num_hits += client_get_hits(cl);
1550 switch (client_get_state(cl))
1552 case Client_Connecting: stat->num_connecting++; break;
1553 case Client_Working: stat->num_working++; break;
1554 case Client_Idle: stat->num_idle++; break;
1555 case Client_Failed: stat->num_failed++; break;
1556 case Client_Error: stat->num_error++; break;
1561 stat->num_records = se->total_records;
1563 stat->num_clients = count;
1566 static struct record_metadata *record_metadata_init(
1567 NMEM nmem, const char *value, const char *norm,
1568 enum conf_metadata_type type,
1569 struct _xmlAttr *attr)
1571 struct record_metadata *rec_md = record_metadata_create(nmem);
1572 struct record_metadata_attr **attrp = &rec_md->attributes;
1574 for (; attr; attr = attr->next)
1576 if (attr->children && attr->children->content)
1578 if (strcmp((const char *) attr->name, "type")
1579 && strcmp((const char *) attr->name, "empty"))
1580 { /* skip the "type" + "empty" attribute..
1581 The "Type" is already part of the element in output
1582 (md-%s) and so repeating it here is redundant */
1583 *attrp = nmem_malloc(nmem, sizeof(**attrp));
1585 nmem_strdup(nmem, (const char *) attr->name);
1587 nmem_strdup(nmem, (const char *) attr->children->content);
1588 attrp = &(*attrp)->next;
1596 case Metadata_type_generic:
1597 case Metadata_type_skiparticle:
1600 rec_md->data.text.disp = nmem_strdup(nmem, value);
1601 rec_md->data.text.norm = nmem_strdup(nmem, norm);
1605 if (strstr(value, "://")) /* looks like a URL */
1606 rec_md->data.text.disp = nmem_strdup(nmem, value);
1608 rec_md->data.text.disp =
1609 normalize7bit_generic(nmem_strdup(nmem, value), " ,/.:([");
1610 rec_md->data.text.norm = rec_md->data.text.disp;
1612 rec_md->data.text.sort = 0;
1613 rec_md->data.text.snippet = 0;
1615 case Metadata_type_year:
1616 case Metadata_type_date:
1621 if (type == Metadata_type_date)
1623 if (extract7bit_dates((char *) value, &first, &last, longdate) < 0)
1626 rec_md->data.number.min = first;
1627 rec_md->data.number.max = last;
1630 case Metadata_type_float:
1631 rec_md->data.fnumber = atof(value);
1633 case Metadata_type_relevance:
1634 case Metadata_type_position:
1635 case Metadata_type_retrieval:
1641 static void mergekey_norm_wr(pp2_charset_fact_t charsets,
1642 WRBUF norm_wr, const char *value)
1644 const char *norm_str;
1645 pp2_charset_token_t prt =
1646 pp2_charset_token_create(charsets, "mergekey");
1648 pp2_charset_token_first(prt, value, 0);
1649 while ((norm_str = pp2_charset_token_next(prt)))
1653 if (wrbuf_len(norm_wr))
1654 wrbuf_puts(norm_wr, " ");
1655 wrbuf_puts(norm_wr, norm_str);
1658 pp2_charset_token_destroy(prt);
1661 static int get_mergekey_from_doc(xmlDoc *doc, xmlNode *root, const char *name,
1662 struct conf_service *service, WRBUF norm_wr)
1666 for (n = root->children; n; n = n->next)
1668 if (n->type != XML_ELEMENT_NODE)
1670 if (!strcmp((const char *) n->name, "metadata"))
1672 const char *type = yaz_xml_get_prop(n, "type");
1674 yaz_log(YLOG_FATAL, "Missing type attribute on metadata element. Skipping!");
1676 else if (!strcmp(name, (const char *) type))
1678 xmlChar *value = xmlNodeListGetString(doc, n->children, 1);
1679 if (value && *value)
1681 if (wrbuf_len(norm_wr) > 0)
1682 wrbuf_puts(norm_wr, " ");
1683 wrbuf_puts(norm_wr, name);
1684 mergekey_norm_wr(service->charsets, norm_wr,
1685 (const char *) value);
1696 static const char *get_mergekey(xmlDoc *doc, xmlNode *root,
1697 struct client *cl, int record_no,
1698 struct conf_service *service, NMEM nmem,
1699 const char *session_mergekey)
1701 char *mergekey_norm = 0;
1702 WRBUF norm_wr = wrbuf_alloc();
1703 const char *mergekey;
1705 if (session_mergekey)
1709 nmem_strsplit_escape2(nmem, ",", session_mergekey, &values,
1712 for (i = 0; i < num; i++)
1713 get_mergekey_from_doc(doc, root, values[i], service, norm_wr);
1715 else if ((mergekey = yaz_xml_get_prop(root, "mergekey")))
1717 mergekey_norm_wr(service->charsets, norm_wr, mergekey);
1721 /* no mergekey defined in XSL. Look for mergekey metadata instead */
1723 for (field_id = 0; field_id < service->num_metadata; field_id++)
1725 struct conf_metadata *ser_md = &service->metadata[field_id];
1726 if (ser_md->mergekey != Metadata_mergekey_no)
1728 int r = get_mergekey_from_doc(doc, root, ser_md->name,
1730 if (r == 0 && ser_md->mergekey == Metadata_mergekey_required)
1732 /* no mergekey on this one and it is required..
1733 Generate unique key instead */
1734 wrbuf_rewind(norm_wr);
1741 /* generate unique key if none is not generated already or is empty */
1742 if (wrbuf_len(norm_wr) == 0)
1744 wrbuf_printf(norm_wr, "position: %s-%06d",
1745 client_get_id(cl), record_no);
1749 const char *lead = "content: ";
1750 wrbuf_insert(norm_wr, 0, lead, strlen(lead));
1752 if (wrbuf_len(norm_wr) > 0)
1753 mergekey_norm = nmem_strdup(nmem, wrbuf_cstr(norm_wr));
1754 wrbuf_destroy(norm_wr);
1755 return mergekey_norm;
1758 /** \brief see if metadata for pz:recordfilter exists
1759 \param root xml root element of normalized record
1760 \param sdb session database for client
1761 \retval 0 if there is no metadata for pz:recordfilter
1762 \retval 1 if there is metadata for pz:recordfilter
1764 If there is no pz:recordfilter defined, this function returns 1
1768 static int check_record_filter(xmlNode *root, struct session_database *sdb)
1773 s = session_setting_oneval(sdb, PZ_RECORDFILTER);
1778 for (n = root->children; n; n = n->next)
1780 if (n->type != XML_ELEMENT_NODE)
1782 if (!strcmp((const char *) n->name, "metadata"))
1784 const char *type = yaz_xml_get_prop(n, "type");
1791 if ((eq = strchr(s, '=')))
1793 else if ((eq = strchr(s, '~')))
1799 if (len == strlen((const char *)type) &&
1800 !memcmp((const char *) type, s, len))
1802 xmlChar *value = xmlNodeGetContent(n);
1803 if (value && *value)
1806 (substring && strstr((const char *) value, eq+1)) ||
1807 (!substring && !strcmp((const char *) value, eq + 1)))
1818 static int ingest_to_cluster(struct client *cl,
1824 struct record_metadata_attr *mergekey);
1826 static int ingest_sub_record(struct client *cl, xmlDoc *xdoc, xmlNode *root,
1827 int record_no, NMEM nmem,
1828 struct session_database *sdb,
1829 struct record_metadata_attr *mergekeys)
1832 struct session *se = client_get_session(cl);
1833 WRBUF wrbuf_disp, wrbuf_norm;
1835 if (!check_record_filter(root, sdb))
1837 session_log(se, YLOG_LOG,
1838 "Filtered out record no %d from %s",
1839 record_no, sdb->database->id);
1842 wrbuf_disp = wrbuf_alloc();
1843 wrbuf_norm = wrbuf_alloc();
1844 session_enter(se, "ingest_sub_record");
1845 if (client_get_session(cl) == se && se->relevance)
1846 ret = ingest_to_cluster(cl, wrbuf_disp, wrbuf_norm,
1847 xdoc, root, record_no, mergekeys);
1848 session_leave(se, "ingest_sub_record");
1849 wrbuf_destroy(wrbuf_norm);
1850 wrbuf_destroy(wrbuf_disp);
1854 /** \brief ingest XML record
1855 \param cl client holds the result set for record
1856 \param rec record buffer (0 terminated)
1857 \param record_no record position (1, 2, ..)
1858 \param nmem working NMEM
1863 int ingest_record(struct client *cl, const char *rec,
1864 int record_no, NMEM nmem)
1866 struct session *se = client_get_session(cl);
1867 struct session_database *sdb = client_get_database(cl);
1868 struct conf_service *service = se->service;
1869 xmlDoc *xdoc = normalize_record(se, sdb, service, rec, nmem);
1870 int r = ingest_xml_record(cl, xdoc, record_no, nmem, 0);
1871 client_store_xdoc(cl, record_no, xdoc);
1875 int ingest_xml_record(struct client *cl, xmlDoc *xdoc,
1876 int record_no, NMEM nmem, int cached_copy)
1878 struct session *se = client_get_session(cl);
1879 struct session_database *sdb = client_get_database(cl);
1880 struct conf_service *service = se->service;
1886 if (global_parameters.dump_records)
1888 session_log(se, YLOG_LOG, "Normalized record from %s",
1893 root = xmlDocGetRootElement(xdoc);
1895 if (!strcmp((const char *) root->name, "cluster"))
1897 int no_merge_keys = 0;
1898 int no_merge_dups = 0;
1900 struct record_metadata_attr *mk = 0;
1902 for (sroot = root->children; sroot; sroot = sroot->next)
1903 if (sroot->type == XML_ELEMENT_NODE &&
1904 !strcmp((const char *) sroot->name, "record"))
1906 struct record_metadata_attr **mkp;
1907 const char *mergekey_norm =
1908 get_mergekey(xdoc, sroot, cl, record_no, service, nmem,
1915 for (mkp = &mk; *mkp; mkp = &(*mkp)->next)
1916 if (!strcmp((*mkp)->value, mergekey_norm))
1920 *mkp = (struct record_metadata_attr*)
1921 nmem_malloc(nmem, sizeof(**mkp));
1923 (*mkp)->value = nmem_strdup(nmem, mergekey_norm);
1930 if (no_merge_keys > 1 || no_merge_dups > 0)
1932 yaz_log(YLOG_LOG, "Got %d mergekeys, %d dups for position %d",
1933 no_merge_keys, no_merge_dups, record_no);
1935 for (sroot = root->children; !r && sroot; sroot = sroot->next)
1936 if (sroot->type == XML_ELEMENT_NODE &&
1937 !strcmp((const char *) sroot->name, "record"))
1940 insert_settings_values(sdb, xdoc, root, service);
1941 r = ingest_sub_record(cl, xdoc, sroot, record_no, nmem, sdb,
1945 else if (!strcmp((const char *) root->name, "record"))
1947 const char *mergekey_norm =
1948 get_mergekey(xdoc, root, cl, record_no, service, nmem,
1952 struct record_metadata_attr *mk = (struct record_metadata_attr*)
1953 nmem_malloc(nmem, sizeof(*mk));
1955 mk->value = nmem_strdup(nmem, mergekey_norm);
1959 insert_settings_values(sdb, xdoc, root, service);
1960 r = ingest_sub_record(cl, xdoc, root, record_no, nmem, sdb, mk);
1965 session_log(se, YLOG_WARN, "Bad pz root element: %s",
1966 (const char *) root->name);
1973 // struct conf_metadata *ser_md = &service->metadata[md_field_id];
1974 // struct record_metadata *rec_md = record->metadata[md_field_id];
1975 static int match_metadata_local(struct conf_service *service,
1976 struct conf_metadata *ser_md,
1977 struct record_metadata *rec_md0,
1978 char **values, int num_v)
1981 struct record_metadata *rec_md = rec_md0;
1983 WRBUF text_wr = wrbuf_alloc();
1984 for (i = 0; i < num_v; )
1988 if (ser_md->type == Metadata_type_year
1989 || ser_md->type == Metadata_type_date)
1991 int y = atoi(values[i]);
1992 if (y >= rec_md->data.number.min
1993 && y <= rec_md->data.number.max)
2000 val_wr = wrbuf_alloc();
2001 mergekey_norm_wr(service->charsets, val_wr, values[i]);
2003 wrbuf_rewind(text_wr);
2004 mergekey_norm_wr(service->charsets, text_wr,
2005 rec_md->data.text.disp);
2006 if (!strcmp(wrbuf_cstr(val_wr), wrbuf_cstr(text_wr)))
2009 rec_md = rec_md->next;
2014 wrbuf_destroy(val_wr);
2019 wrbuf_destroy(val_wr);
2020 wrbuf_destroy(text_wr);
2021 return i < num_v ? 1 : 0;
2024 int session_check_cluster_limit(struct session *se, struct record_cluster *rec)
2027 struct conf_service *service = se->service;
2031 NMEM nmem_tmp = nmem_create();
2033 for (i = 0; (name = facet_limits_get(se->facet_limits, i, &value)); i++)
2036 for (j = 0; j < service->num_metadata; j++)
2038 struct conf_metadata *md = service->metadata + j;
2039 if (!strcmp(md->name, name) && md->limitcluster)
2044 conf_service_metadata_field_id(service,
2047 if (md_field_id < 0)
2053 nmem_strsplit_escape2(nmem_tmp, "|", value, &values,
2056 if (!match_metadata_local(service,
2057 &service->metadata[md_field_id],
2058 rec->metadata[md_field_id],
2067 nmem_destroy(nmem_tmp);
2071 // Skip record on non-zero
2072 static int check_limit_local(struct client *cl,
2073 struct record *record,
2076 int skip_record = 0;
2077 struct session *se = client_get_session(cl);
2078 struct conf_service *service = se->service;
2079 NMEM nmem_tmp = nmem_create();
2080 struct session_database *sdb = client_get_database(cl);
2082 while (!skip_record)
2088 client_get_facet_limit_local(cl, sdb, &l, nmem_tmp,
2093 if (!strcmp(name, "*"))
2095 for (md_field_id = 0; md_field_id < service->num_metadata;
2098 if (match_metadata_local(
2100 &service->metadata[md_field_id],
2101 record->metadata[md_field_id],
2105 if (md_field_id == service->num_metadata)
2110 md_field_id = conf_service_metadata_field_id(service, name);
2111 if (md_field_id < 0)
2116 if (!match_metadata_local(
2118 &service->metadata[md_field_id],
2119 record->metadata[md_field_id],
2126 nmem_destroy(nmem_tmp);
2130 static int ingest_to_cluster(struct client *cl,
2136 struct record_metadata_attr *merge_keys)
2139 struct session *se = client_get_session(cl);
2140 struct conf_service *service = se->service;
2141 int term_factor = 1;
2142 struct record_cluster *cluster;
2143 struct record_metadata **metadata0;
2144 struct session_database *sdb = client_get_database(cl);
2145 NMEM ingest_nmem = 0;
2146 char **rank_values = 0;
2148 struct record *record = record_create(se->nmem,
2149 service->num_metadata,
2150 service->num_sortkeys, cl,
2153 for (n = root->children; n; n = n->next)
2155 if (n->type != XML_ELEMENT_NODE)
2157 if (!strcmp((const char *) n->name, "metadata"))
2159 struct conf_metadata *ser_md = 0;
2160 struct record_metadata **wheretoput = 0;
2161 struct record_metadata *rec_md = 0;
2162 int md_field_id = -1;
2164 const char *type = yaz_xml_get_prop(n, "type");
2170 = conf_service_metadata_field_id(service, (const char *) type);
2171 if (md_field_id < 0)
2173 if (se->number_of_warnings_unknown_metadata == 0)
2175 session_log(se, YLOG_WARN,
2176 "Ignoring unknown metadata element: %s", type);
2178 se->number_of_warnings_unknown_metadata++;
2182 wrbuf_rewind(wrbuf_disp);
2183 value0 = xmlNodeListGetString(xdoc, n->children, 1);
2184 if (!value0 || !*value0)
2186 const char *empty = yaz_xml_get_prop(n, "empty");
2189 wrbuf_puts(wrbuf_disp, (const char *) empty);
2193 wrbuf_puts(wrbuf_disp, (const char *) value0);
2197 ser_md = &service->metadata[md_field_id];
2199 // non-merged metadata
2200 rec_md = record_metadata_init(se->nmem, wrbuf_cstr(wrbuf_disp), 0,
2201 ser_md->type, n->properties);
2204 session_log(se, YLOG_WARN, "bad metadata data '%s' "
2205 "for element '%s'", wrbuf_cstr(wrbuf_disp), type);
2209 if (ser_md->type == Metadata_type_generic)
2211 WRBUF w = wrbuf_alloc();
2212 if (relevance_snippet(se->relevance,
2213 wrbuf_cstr(wrbuf_disp), ser_md->name, w))
2214 rec_md->data.text.snippet = nmem_strdup(se->nmem,
2220 wheretoput = &record->metadata[md_field_id];
2222 wheretoput = &(*wheretoput)->next;
2223 *wheretoput = rec_md;
2227 if (check_limit_local(cl, record, record_no))
2231 cluster = reclist_insert(se->reclist, se->relevance, service, record,
2232 merge_keys, &se->total_merged);
2235 return 0; // complete match with existing record
2239 const char *use_term_factor_str =
2240 session_setting_oneval(sdb, PZ_TERMLIST_TERM_FACTOR);
2241 if (use_term_factor_str && use_term_factor_str[0] == '1')
2243 int maxrecs = client_get_maxrecs(cl);
2244 int hits = (int) client_get_hits(cl);
2245 term_factor = MAX(hits, maxrecs) / MAX(1, maxrecs);
2246 assert(term_factor >= 1);
2247 session_log(se, YLOG_DEBUG, "Using term factor: %d (%d / %d)",
2248 term_factor, MAX(hits, maxrecs), MAX(1, maxrecs));
2252 if (global_parameters.dump_records)
2253 session_log(se, YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
2254 sdb->database->id, record_no);
2256 // original metadata, to check if first existence of a field
2257 metadata0 = xmalloc(sizeof(*metadata0) * service->num_metadata);
2258 memcpy(metadata0, cluster->metadata,
2259 sizeof(*metadata0) * service->num_metadata);
2261 ingest_nmem = nmem_create();
2264 yaz_log(YLOG_LOG, "local in sort : %s", se->rank);
2265 nmem_strsplit_escape2(ingest_nmem, ",", se->rank, &rank_values,
2266 &rank_num, 1, '\\', 1);
2269 // now parsing XML record and adding data to cluster or record metadata
2270 for (n = root->children; n; n = n->next)
2272 if (n->type != XML_ELEMENT_NODE)
2274 if (!strcmp((const char *) n->name, "metadata"))
2276 struct conf_metadata *ser_md = 0;
2277 struct conf_sortkey *ser_sk = 0;
2278 struct record_metadata **wheretoput = 0;
2279 struct record_metadata *rec_md = 0;
2280 int md_field_id = -1;
2281 int sk_field_id = -1;
2282 const char *rank = 0;
2283 const char *xml_rank = 0;
2284 const char *type = 0;
2287 type = yaz_xml_get_prop(n, "type");
2292 = conf_service_metadata_field_id(service, (const char *) type);
2293 if (md_field_id < 0)
2296 ser_md = &service->metadata[md_field_id];
2298 if (ser_md->sortkey_offset >= 0)
2300 sk_field_id = ser_md->sortkey_offset;
2301 ser_sk = &service->sortkeys[sk_field_id];
2304 wrbuf_rewind(wrbuf_disp);
2305 wrbuf_rewind(wrbuf_norm);
2307 value0 = xmlNodeListGetString(xdoc, n->children, 1);
2308 if (!value0 || !*value0)
2315 if (ser_md->icurule)
2317 run_icu(se, ser_md->icurule, (const char *) value0,
2318 wrbuf_norm, wrbuf_disp);
2319 yaz_log(YLOG_LOG, "run_icu input=%s norm=%s disp=%s",
2320 (const char *) value0,
2321 wrbuf_cstr(wrbuf_norm), wrbuf_cstr(wrbuf_disp));
2322 rec_md = record_metadata_init(se->nmem, wrbuf_cstr(wrbuf_disp),
2323 wrbuf_cstr(wrbuf_norm),
2328 wrbuf_puts(wrbuf_disp, (const char *) value0);
2329 rec_md = record_metadata_init(se->nmem, wrbuf_cstr(wrbuf_disp),
2336 // see if the field was not in cluster already (from beginning)
2343 for (i = 0; i < rank_num; i++)
2345 const char *val = rank_values[i];
2346 const char *cp = strchr(val, '=');
2349 if ((cp - val) == strlen((const char *) type)
2350 && !memcmp(val, type, cp - val))
2359 xml_rank = yaz_xml_get_prop(n, "rank");
2360 rank = xml_rank ? (const char *) xml_rank : ser_md->rank;
2363 wheretoput = &cluster->metadata[md_field_id];
2365 if (ser_md->merge == Metadata_merge_first)
2367 if (!metadata0[md_field_id])
2370 wheretoput = &(*wheretoput)->next;
2371 *wheretoput = rec_md;
2374 else if (ser_md->merge == Metadata_merge_unique)
2378 if (!strcmp((const char *) (*wheretoput)->data.text.norm,
2379 rec_md->data.text.norm))
2381 wheretoput = &(*wheretoput)->next;
2384 *wheretoput = rec_md;
2386 else if (ser_md->merge == Metadata_merge_longest)
2389 || strlen(rec_md->data.text.norm)
2390 > strlen((*wheretoput)->data.text.norm))
2392 *wheretoput = rec_md;
2395 pp2_charset_token_t prt;
2396 const char *sort_str = 0;
2398 ser_sk->type == Metadata_type_skiparticle;
2400 if (!cluster->sortkeys[sk_field_id])
2401 cluster->sortkeys[sk_field_id] =
2402 nmem_malloc(se->nmem,
2403 sizeof(union data_types));
2406 pp2_charset_token_create(service->charsets, "sort");
2408 pp2_charset_token_first(prt, rec_md->data.text.disp,
2411 pp2_charset_token_next(prt);
2413 sort_str = pp2_get_sort(prt);
2415 cluster->sortkeys[sk_field_id]->text.disp =
2416 rec_md->data.text.disp;
2419 sort_str = rec_md->data.text.disp;
2420 session_log(se, YLOG_WARN,
2421 "Could not make sortkey. Bug #1858");
2423 cluster->sortkeys[sk_field_id]->text.sort =
2424 nmem_strdup(se->nmem, sort_str);
2425 pp2_charset_token_destroy(prt);
2429 else if (ser_md->merge == Metadata_merge_all)
2432 wheretoput = &(*wheretoput)->next;
2433 *wheretoput = rec_md;
2435 else if (ser_md->merge == Metadata_merge_range)
2439 *wheretoput = rec_md;
2441 cluster->sortkeys[sk_field_id]
2446 int this_min = rec_md->data.number.min;
2447 int this_max = rec_md->data.number.max;
2448 if (this_min < (*wheretoput)->data.number.min)
2449 (*wheretoput)->data.number.min = this_min;
2450 if (this_max > (*wheretoput)->data.number.max)
2451 (*wheretoput)->data.number.max = this_max;
2455 // ranking of _all_ fields enabled ...
2458 relevance_countwords(se->relevance, cluster,
2459 wrbuf_cstr(wrbuf_disp),
2460 rank, ser_md->name);
2462 // construct facets ... unless the client already has reported them
2463 if (ser_md->termlist && !client_has_facet(cl, (char *) type))
2465 if (ser_md->type == Metadata_type_year)
2468 sprintf(year, "%d", rec_md->data.number.max);
2470 add_facet(se, (char *) type, year, term_factor, cl);
2471 if (rec_md->data.number.max != rec_md->data.number.min)
2473 sprintf(year, "%d", rec_md->data.number.min);
2474 add_facet(se, (char *) type, year, term_factor, cl);
2478 add_facet(se, type, wrbuf_cstr(wrbuf_disp), term_factor, cl);
2483 if (se->number_of_warnings_unknown_elements == 0)
2484 session_log(se, YLOG_WARN,
2485 "Unexpected element in internal record: %s", n->name);
2486 se->number_of_warnings_unknown_elements++;
2489 nmem_destroy(ingest_nmem);
2491 relevance_donerecord(se->relevance, cluster);
2492 se->total_records++;
2497 void session_log(struct session *s, int level, const char *fmt, ...)
2503 yaz_vsnprintf(buf, sizeof(buf)-30, fmt, ap);
2504 yaz_log(level, "Session %u: %s", s ? s->session_id : 0, buf);
2512 * c-file-style: "Stroustrup"
2513 * indent-tabs-mode: nil
2515 * vim: shiftwidth=4 tabstop=8 expandtab