9e238a68793c90ba6014f9739b509555fabe6160
[pazpar2-moved-to-github.git] / src / session.c
1 /* This file is part of Pazpar2.
2    Copyright (C) Index Data
3
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
7 version.
8
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
12 for more details.
13
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
17
18 */
19
20 /** \file session.c
21     \brief high-level logic; mostly user sessions and settings
22 */
23
24 #if HAVE_CONFIG_H
25 #include <config.h>
26 #endif
27
28 #include <time.h>
29 #include <stdlib.h>
30 #include <stdio.h>
31 #include <string.h>
32 #if HAVE_SYS_TIME_H
33 #include <sys/time.h>
34 #endif
35 #if HAVE_UNISTD_H
36 #include <unistd.h>
37 #endif
38 #ifdef WIN32
39 #include <windows.h>
40 #endif
41 #include <signal.h>
42 #include <ctype.h>
43 #include <assert.h>
44 #include <math.h>
45
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>
54 #include <yaz/nmem.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>
60
61 #define USE_TIMING 0
62 #if USE_TIMING
63 #include <yaz/timing.h>
64 #endif
65
66 #include "ppmutex.h"
67 #include "parameters.h"
68 #include "session.h"
69 #include "eventl.h"
70 #include "http.h"
71 #include "termlists.h"
72 #include "reclists.h"
73 #include "relevance.h"
74 #include "database.h"
75 #include "client.h"
76 #include "settings.h"
77 #include "normalize7bit.h"
78
79 #include <libxml/tree.h>
80
81 #define MAX_CHUNK 15
82
83 #define MAX(a,b) ((a)>(b)?(a):(b))
84
85 // Note: Some things in this structure will eventually move to configuration
86 struct parameters global_parameters =
87 {
88     0,   // dump_records
89     0,   // debug_mode
90     0,   // predictable sessions
91 };
92
93 struct client_list {
94     struct client *client;
95     struct client_list *next;
96 };
97
98 /* session counting (1) , disable client counting (0) */
99 static YAZ_MUTEX g_session_mutex = 0;
100 static int no_sessions = 0;
101
102 static int session_use(int delta)
103 {
104     int sessions;
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);
113     return sessions;
114 }
115
116 int sessions_count(void)
117 {
118     return session_use(0);
119 }
120
121 static void log_xml_doc(xmlDoc *doc)
122 {
123     FILE *lf = yaz_log_file();
124     xmlChar *result = 0;
125     int len = 0;
126 #if LIBXML_VERSION >= 20600
127     xmlDocDumpFormatMemory(doc, &result, &len, 1);
128 #else
129     xmlDocDumpMemory(doc, &result, &len);
130 #endif
131     if (lf && len)
132     {
133         (void) fwrite(result, 1, len, lf);
134         fprintf(lf, "\n");
135     }
136     xmlFree(result);
137 }
138
139 static void session_enter(struct session *s, const char *caller)
140 {
141     if (caller)
142         session_log(s, YLOG_DEBUG, "Session lock by %s", caller);
143     yaz_mutex_enter(s->session_mutex);
144 }
145
146 static void session_leave(struct session *s, const char *caller)
147 {
148     yaz_mutex_leave(s->session_mutex);
149     if (caller)
150         session_log(s, YLOG_DEBUG, "Session unlock by %s", caller);
151 }
152
153 static int run_icu(struct session *s, const char *icu_chain_id,
154                    const char *value,
155                    WRBUF norm_wr, WRBUF disp_wr)
156 {
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);
161     if (!prt)
162     {
163         session_log(s, YLOG_FATAL,
164                     "Unknown ICU chain '%s'", icu_chain_id);
165         return 0;
166     }
167     pp2_charset_token_first(prt, value, 0);
168     while ((facet_component = pp2_charset_token_next(prt)))
169     {
170         const char *display_component;
171         if (*facet_component)
172         {
173             if (wrbuf_len(norm_wr))
174                 wrbuf_puts(norm_wr, " ");
175             wrbuf_puts(norm_wr, facet_component);
176         }
177         display_component = pp2_get_display(prt);
178         if (display_component)
179         {
180             if (wrbuf_len(disp_wr))
181                 wrbuf_puts(disp_wr, " ");
182             wrbuf_puts(disp_wr, display_component);
183         }
184     }
185     pp2_charset_token_destroy(prt);
186     return 1;
187 }
188
189 static void session_normalize_facet(struct session *s,
190                                     const char *type, const char *value,
191                                     WRBUF display_wrbuf, WRBUF facet_wrbuf)
192 {
193     struct conf_service *service = s->service;
194     int i;
195     const char *icu_chain_id = 0;
196
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;
200     if (!icu_chain_id)
201         icu_chain_id = "facet";
202
203     run_icu(s, icu_chain_id, value, facet_wrbuf, display_wrbuf);
204 }
205
206 void add_facet(struct session *s, const char *type, const char *value, int count)
207 {
208     WRBUF facet_wrbuf = wrbuf_alloc();
209     WRBUF display_wrbuf = wrbuf_alloc();
210
211     session_normalize_facet(s, type, value, display_wrbuf, facet_wrbuf);
212
213     if (wrbuf_len(facet_wrbuf))
214     {
215         struct named_termlist **tp = &s->termlists;
216         for (; (*tp); tp = &(*tp)->next)
217             if (!strcmp((*tp)->name, type))
218                 break;
219         if (!*tp)
220         {
221             *tp = nmem_malloc(s->nmem, sizeof(**tp));
222             (*tp)->name = nmem_strdup(s->nmem, type);
223             (*tp)->termlist = termlist_create(s->nmem);
224             (*tp)->next = 0;
225         }
226         termlist_insert((*tp)->termlist, wrbuf_cstr(display_wrbuf),
227                         wrbuf_cstr(facet_wrbuf), count);
228     }
229     wrbuf_destroy(facet_wrbuf);
230     wrbuf_destroy(display_wrbuf);
231 }
232
233 static xmlDoc *record_to_xml(struct session *se,
234                              struct session_database *sdb, const char *rec)
235 {
236     struct database *db = sdb->database;
237     xmlDoc *rdoc = 0;
238
239     rdoc = xmlParseMemory(rec, strlen(rec));
240
241     if (!rdoc)
242     {
243         session_log(se, YLOG_WARN, "Non-wellformed XML");
244         return 0;
245     }
246
247     if (global_parameters.dump_records)
248     {
249         session_log(se, YLOG_LOG, "Un-normalized record from %s", db->id);
250         log_xml_doc(rdoc);
251     }
252
253     return rdoc;
254 }
255
256 #define MAX_XSLT_ARGS 16
257
258 // Add static values from session database settings if applicable
259 static void insert_settings_parameters(struct session_database *sdb,
260                                        struct conf_service *service,
261                                        char **parms,
262                                        NMEM nmem)
263 {
264     int i;
265     int nparms = 0;
266     int offset = 0;
267
268     for (i = 0; i < service->num_metadata; i++)
269     {
270         struct conf_metadata *md = &service->metadata[i];
271         int setting;
272
273         if (md->setting == Metadata_setting_parameter &&
274             (setting = settings_lookup_offset(service, md->name)) >= 0)
275         {
276             const char *val = session_setting_oneval(sdb, setting);
277             if (val && nparms < MAX_XSLT_ARGS)
278             {
279                 char *buf;
280                 int len = strlen(val);
281                 buf = nmem_malloc(nmem, len + 3);
282                 buf[0] = '\'';
283                 strcpy(buf + 1, val);
284                 buf[len+1] = '\'';
285                 buf[len+2] = '\0';
286                 parms[offset++] = md->name;
287                 parms[offset++] = buf;
288                 nparms++;
289             }
290         }
291     }
292     parms[offset] = 0;
293 }
294
295 // Add static values from session database settings if applicable
296 static void insert_settings_values(struct session_database *sdb, xmlDoc *doc,
297                                    xmlNode *root,
298                                    struct conf_service *service)
299 {
300     int i;
301
302     for (i = 0; i < service->num_metadata; i++)
303     {
304         struct conf_metadata *md = &service->metadata[i];
305         int offset;
306
307         if (md->setting == Metadata_setting_postproc &&
308             (offset = settings_lookup_offset(service, md->name)) >= 0)
309         {
310             const char *val = session_setting_oneval(sdb, offset);
311             if (val)
312             {
313                 xmlNode *n = xmlNewTextChild(root, 0, (xmlChar *) "metadata",
314                                              (xmlChar *) val);
315                 xmlSetProp(n, (xmlChar *) "type", (xmlChar *) md->name);
316             }
317         }
318     }
319 }
320
321 static xmlDoc *normalize_record(struct session *se,
322                                 struct session_database *sdb,
323                                 struct conf_service *service,
324                                 const char *rec, NMEM nmem)
325 {
326     xmlDoc *rdoc = record_to_xml(se, sdb, rec);
327
328     if (rdoc)
329     {
330         char *parms[MAX_XSLT_ARGS*2+1];
331
332         insert_settings_parameters(sdb, service, parms, nmem);
333
334         if (normalize_record_transform(sdb->map, &rdoc, (const char **)parms))
335         {
336             session_log(se, YLOG_WARN, "Normalize failed");
337         }
338     }
339     return rdoc;
340 }
341
342 void session_settings_dump(struct session *se,
343                            struct session_database *db,
344                            WRBUF w)
345 {
346     if (db->settings)
347     {
348         int i, num = db->num_settings;
349         for (i = 0; i < num; i++)
350         {
351             struct setting *s = db->settings[i];
352             for (;s ; s = s->next)
353             {
354                 wrbuf_puts(w, "<set name=\"");
355                 wrbuf_xmlputs(w, s->name);
356                 wrbuf_puts(w, "\" value=\"");
357                 wrbuf_xmlputs(w, s->value);
358                 wrbuf_puts(w, "\"/>");
359             }
360             if (db->settings[i])
361                 wrbuf_puts(w, "\n");
362         }
363     }
364 }
365
366 // Retrieve first defined value for 'name' for given database.
367 // Will be extended to take into account user associated with session
368 const char *session_setting_oneval(struct session_database *db, int offset)
369 {
370     if (offset >= db->num_settings || !db->settings[offset])
371         return "";
372     return db->settings[offset]->value;
373 }
374
375 // Prepare XSLT stylesheets for record normalization
376 // Structures are allocated on the session_wide nmem to avoid having
377 // to recompute this for every search. This would lead
378 // to leaking if a single session was to repeatedly change the PZ_XSLT
379 // setting. However, this is not a realistic use scenario.
380 static int prepare_map(struct session *se, struct session_database *sdb)
381 {
382     if (sdb->settings && !sdb->map)
383     {
384         const char *s;
385
386         if (sdb->settings[PZ_XSLT] &&
387             (s = session_setting_oneval(sdb, PZ_XSLT)))
388         {
389             char auto_stylesheet[256];
390
391             if (!strcmp(s, "auto"))
392             {
393                 const char *request_syntax = session_setting_oneval(
394                     sdb, PZ_REQUESTSYNTAX);
395                 if (request_syntax)
396                 {
397                     char *cp;
398                     yaz_snprintf(auto_stylesheet, sizeof(auto_stylesheet),
399                                  "%s.xsl", request_syntax);
400                     for (cp = auto_stylesheet; *cp; cp++)
401                     {
402                         /* deliberately only consider ASCII */
403                         if (*cp > 32 && *cp < 127)
404                             *cp = tolower(*cp);
405                     }
406                     s = auto_stylesheet;
407                 }
408                 else
409                 {
410                     session_log(se, YLOG_WARN,
411                                 "No pz:requestsyntax for auto stylesheet");
412                 }
413             }
414             sdb->map = normalize_cache_get(se->normalize_cache,
415                                            se->service, s);
416             if (!sdb->map)
417                 return -1;
418         }
419     }
420     return 0;
421 }
422
423 // called if watch should be removed because http_channel is to be destroyed
424 static void session_watch_cancel(void *data, struct http_channel *c,
425                                  void *data2)
426 {
427     struct session_watchentry *ent = data;
428
429     ent->fun = 0;
430     ent->data = 0;
431     ent->obs = 0;
432 }
433
434 // set watch. Returns 0=OK, -1 if watch is already set
435 int session_set_watch(struct session *s, int what,
436                       session_watchfun fun, void *data,
437                       struct http_channel *chan)
438 {
439     int ret;
440     session_enter(s, "session_set_watch");
441     if (s->watchlist[what].fun)
442         ret = -1;
443     else
444     {
445
446         s->watchlist[what].fun = fun;
447         s->watchlist[what].data = data;
448         s->watchlist[what].obs = http_add_observer(chan, &s->watchlist[what],
449                                                    session_watch_cancel);
450         ret = 0;
451     }
452     session_leave(s, "session_set_watch");
453     return ret;
454 }
455
456 void session_alert_watch(struct session *s, int what)
457 {
458     assert(s);
459     session_enter(s, "session_alert_watch");
460     if (s->watchlist[what].fun)
461     {
462         /* our watch is no longer associated with http_channel */
463         void *data;
464         session_watchfun fun;
465
466         http_remove_observer(s->watchlist[what].obs);
467         fun  = s->watchlist[what].fun;
468         data = s->watchlist[what].data;
469
470         /* reset watch before fun is invoked - in case fun wants to set
471            it again */
472         s->watchlist[what].fun = 0;
473         s->watchlist[what].data = 0;
474         s->watchlist[what].obs = 0;
475
476         session_leave(s, "session_alert_watch");
477         session_log(s, YLOG_DEBUG,
478                     "Alert Watch: %d calling function: %p", what, fun);
479         fun(data);
480     }
481     else
482         session_leave(s,"session_alert_watch");
483 }
484
485 //callback for grep_databases
486 static void select_targets_callback(struct session *se,
487                                     struct session_database *db)
488 {
489     struct client *cl;
490     struct client_list *l;
491
492     for (l = se->clients_cached; l; l = l->next)
493         if (client_get_database(l->client) == db)
494             break;
495
496     if (l)
497         cl = l->client;
498     else
499     {
500         cl = client_create(db->database->id);
501         client_set_database(cl, db);
502
503         l = xmalloc(sizeof(*l));
504         l->client = cl;
505         l->next = se->clients_cached;
506         se->clients_cached = l;
507     }
508     /* set session always. If may be 0 if client is not active */
509     client_set_session(cl, se);
510
511     l = xmalloc(sizeof(*l));
512     l->client = cl;
513     l->next = se->clients_active;
514     se->clients_active = l;
515 }
516
517 static void session_reset_active_clients(struct session *se,
518                                          struct client_list *new_list)
519 {
520     struct client_list *l;
521
522     session_enter(se, "session_reset_active_clients");
523     l = se->clients_active;
524     se->clients_active = new_list;
525     session_leave(se, "session_reset_active_clients");
526
527     while (l)
528     {
529         struct client_list *l_next = l->next;
530
531         client_lock(l->client);
532         client_set_session(l->client, 0); /* mark client inactive */
533         client_unlock(l->client);
534
535         xfree(l);
536         l = l_next;
537     }
538 }
539
540 static void session_remove_cached_clients(struct session *se)
541 {
542     struct client_list *l;
543
544     session_reset_active_clients(se, 0);
545
546     session_enter(se, "session_remove_cached_clients");
547     l = se->clients_cached;
548     se->clients_cached = 0;
549     session_leave(se, "session_remove_cached_clients");
550
551     while (l)
552     {
553         struct client_list *l_next = l->next;
554         client_lock(l->client);
555         client_set_session(l->client, 0);
556         client_set_database(l->client, 0);
557         client_unlock(l->client);
558         client_destroy(l->client);
559         xfree(l);
560         l = l_next;
561     }
562 }
563
564 // Associates a set of clients with a session;
565 // Note: Session-databases represent databases with per-session
566 // setting overrides
567 static int select_targets(struct session *se, const char *filter)
568 {
569     return session_grep_databases(se, filter, select_targets_callback);
570 }
571
572 int session_active_clients(struct session *s)
573 {
574     struct client_list *l;
575     int res = 0;
576
577     for (l = s->clients_active; l; l = l->next)
578         if (client_is_active(l->client))
579             res++;
580
581     return res;
582 }
583
584 int session_is_preferred_clients_ready(struct session *s)
585 {
586     struct client_list *l;
587     int res = 0;
588
589     for (l = s->clients_active; l; l = l->next)
590         if (client_is_active_preferred(l->client))
591             res++;
592     session_log(s, YLOG_DEBUG, "Has %d active preferred clients.", res);
593     return res == 0;
594 }
595
596 static void session_clear_set(struct session *se, struct reclist_sortparms *sp)
597 {
598     reclist_destroy(se->reclist);
599     if (nmem_total(se->nmem))
600         session_log(se, YLOG_DEBUG, "NMEN operation usage %zd",
601                     nmem_total(se->nmem));
602     nmem_reset(se->nmem);
603     se->total_records = se->total_merged = 0;
604     se->termlists = 0;
605     relevance_clear(se->relevance);
606
607     /* reset list of sorted results and clear to relevance search */
608     se->sorted_results = nmem_malloc(se->nmem, sizeof(*se->sorted_results));
609     se->sorted_results->name = nmem_strdup(se->nmem, sp->name);
610     se->sorted_results->increasing = sp->increasing;
611     se->sorted_results->type = sp->type;
612     se->sorted_results->next = 0;
613
614     session_log(se, YLOG_DEBUG, "clear_set session_sort: field=%s increasing=%d type=%d configured",
615             sp->name, sp->increasing, sp->type);
616
617     se->reclist = reclist_create(se->nmem);
618 }
619
620 void session_sort(struct session *se, struct reclist_sortparms *sp,
621                   const char *mergekey, const char *rank)
622 {
623     struct client_list *l;
624     const char *field = sp->name;
625     int increasing = sp->increasing;
626     int type  = sp->type;
627     int clients_research = 0;
628
629     session_enter(se, "session_sort");
630     session_log(se, YLOG_DEBUG, "session_sort field=%s increasing=%d type=%d",
631                 field, increasing, type);
632
633     if (rank && (!se->rank || strcmp(se->rank, rank)))
634     {
635         /* new rank must research/reingest anyway */
636         assert(rank);
637         xfree(se->rank);
638         se->rank = *rank ? xstrdup(rank) : 0;
639         clients_research = 1;
640         session_log(se, YLOG_DEBUG, "session_sort: new rank = %s",
641                     rank);
642     }
643     if (mergekey && (!se->mergekey || strcmp(se->mergekey, mergekey)))
644     {
645         /* new mergekey must research/reingest anyway */
646         assert(mergekey);
647         xfree(se->mergekey);
648         se->mergekey = *mergekey ? xstrdup(mergekey) : 0;
649         clients_research = 1;
650         session_log(se, YLOG_DEBUG, "session_sort: new mergekey = %s",
651                     mergekey);
652     }
653     if (clients_research == 0)
654     {
655         struct reclist_sortparms *sr;
656         for (sr = se->sorted_results; sr; sr = sr->next)
657             if (!reclist_sortparms_cmp(sr, sp))
658                 break;
659         if (sr)
660         {
661             session_log(se, YLOG_DEBUG, "session_sort: field=%s increasing=%d type=%d already fetched",
662                         field, increasing, type);
663             session_leave(se, "session_sort");
664             return;
665         }
666     }
667     session_log(se, YLOG_DEBUG, "session_sort: field=%s increasing=%d type=%d must fetch",
668                 field, increasing, type);
669
670     // We need to reset reclist on every sort that changes the records, not just for position
671     // So if just one client requires new searching, we need to clear set.
672     // Ask each of the client if sorting requires re-search due to native sort
673     // If it does it will require us to
674     for (l = se->clients_active; l; l = l->next)
675     {
676         struct client *cl = l->client;
677         // Assume no re-search is required.
678         client_parse_init(cl, 1);
679         clients_research += client_parse_sort(cl, sp);
680     }
681     if (!clients_research || se->clients_starting)
682     {
683         // A new sorting based on same record set
684         struct reclist_sortparms *sr = nmem_malloc(se->nmem, sizeof(*sr));
685         sr->name = nmem_strdup(se->nmem, field);
686         sr->increasing = increasing;
687         sr->type = type;
688         sr->next = se->sorted_results;
689         se->sorted_results = sr;
690         session_log(se, YLOG_DEBUG, "session_sort: no research/ingesting done");
691         session_leave(se, "session_sort");
692     }
693     else
694     {
695         se->clients_starting = 1;
696         session_log(se, YLOG_DEBUG,
697                     "session_sort: reset results due to %d clients researching",
698                     clients_research);
699         session_clear_set(se, sp);
700         session_log(se, YLOG_DEBUG, "Re- search/ingesting for clients due to change in sort order");
701
702         session_leave(se, "session_sort");
703         for (l = se->clients_active; l; l = l->next)
704         {
705             struct client *cl = l->client;
706             if (client_get_state(cl) == Client_Connecting ||
707                 client_get_state(cl) == Client_Idle ||
708                 client_get_state(cl) == Client_Working) {
709                 client_start_search(cl);
710             }
711             else
712             {
713                 session_log(se, YLOG_DEBUG,
714                             "session_sort: %s: No re-start/ingest in show. "
715                             "Wrong client state: %d",
716                             client_get_id(cl), client_get_state(cl));
717             }
718         }
719         session_enter(se, "session_sort");
720         se->clients_starting = 0;
721         session_leave(se, "session_sort");
722     }
723 }
724
725 void session_stop(struct session *se)
726 {
727     struct client_list *l;
728     session_enter(se, "session_stop1");
729     if (se->clients_starting)
730     {
731         session_leave(se, "session_stop1");
732         return;
733     }
734     se->clients_starting = 1;
735     session_leave(se, "session_stop1");
736
737     session_alert_watch(se, SESSION_WATCH_SHOW);
738     session_alert_watch(se, SESSION_WATCH_BYTARGET);
739     session_alert_watch(se, SESSION_WATCH_TERMLIST);
740     session_alert_watch(se, SESSION_WATCH_SHOW_PREF);
741
742     for (l = se->clients_active; l; l = l->next)
743     {
744         struct client *cl = l->client;
745         client_stop(cl);
746     }
747     session_enter(se, "session_stop2");
748     se->clients_starting = 0;
749     session_leave(se, "session_stop2");
750 }
751
752 enum pazpar2_error_code session_search(struct session *se,
753                                        const char *query,
754                                        const char *startrecs,
755                                        const char *maxrecs,
756                                        const char *filter,
757                                        const char *limit,
758                                        const char **addinfo,
759                                        const char **addinfo2,
760                                        struct reclist_sortparms *sp,
761                                        const char *mergekey,
762                                        const char *rank)
763 {
764     int live_channels = 0;
765     int no_working = 0;
766     int no_failed_query = 0;
767     int no_failed_limit = 0;
768     struct client_list *l;
769
770     session_log(se, YLOG_DEBUG, "Search");
771
772     *addinfo = 0;
773
774     session_enter(se, "session_search0");
775     if (se->clients_starting)
776     {
777         session_leave(se, "session_search0");
778         return PAZPAR2_NO_ERROR;
779     }
780     se->clients_starting = 1;
781     session_leave(se, "session_search0");
782
783     if (se->settings_modified) {
784         session_remove_cached_clients(se);
785     }
786     else
787         session_reset_active_clients(se, 0);
788
789     session_enter(se, "session_search");
790     se->settings_modified = 0;
791
792     if (mergekey)
793     {
794         xfree(se->mergekey);
795         se->mergekey = *mergekey ? xstrdup(mergekey) : 0;
796     }
797     if (rank)
798     {
799         xfree(se->rank);
800         se->rank = *rank ? xstrdup(rank) : 0;
801     }
802
803     session_clear_set(se, sp);
804     relevance_destroy(&se->relevance);
805
806     live_channels = select_targets(se, filter);
807     if (!live_channels)
808     {
809         session_leave(se, "session_search");
810         se->clients_starting = 0;
811         return PAZPAR2_NO_TARGETS;
812     }
813
814     facet_limits_destroy(se->facet_limits);
815     se->facet_limits = facet_limits_create(limit);
816     if (!se->facet_limits)
817     {
818         *addinfo = "limit";
819         session_leave(se, "session_search");
820         se->clients_starting = 0;
821         return PAZPAR2_MALFORMED_PARAMETER_VALUE;
822     }
823
824     session_leave(se, "session_search");
825
826     session_alert_watch(se, SESSION_WATCH_SHOW);
827     session_alert_watch(se, SESSION_WATCH_BYTARGET);
828     session_alert_watch(se, SESSION_WATCH_TERMLIST);
829     session_alert_watch(se, SESSION_WATCH_SHOW_PREF);
830
831     for (l = se->clients_active; l; l = l->next)
832     {
833         int parse_ret;
834         struct client *cl = l->client;
835         client_parse_init(cl, 1);
836         if (prepare_map(se, client_get_database(cl)) < 0)
837             continue;
838
839         parse_ret = client_parse_query(cl, query, se->facet_limits, addinfo2);
840         if (parse_ret == -1)
841             no_failed_query++;
842         else if (parse_ret == -2)
843             no_failed_limit++;
844         else if (parse_ret < 0)
845             no_working++; /* other error, such as bad CCL map */
846         else
847         {
848             client_parse_range(cl, startrecs, maxrecs);
849             client_parse_sort(cl, sp);
850             client_start_search(cl);
851             no_working++;
852         }
853     }
854     session_enter(se, "session_search2");
855     se->clients_starting = 0;
856     session_leave(se, "session_search2");
857     if (no_working == 0)
858     {
859         if (no_failed_query > 0)
860         {
861             *addinfo = "query";
862             return PAZPAR2_MALFORMED_PARAMETER_VALUE;
863         }
864         else if (no_failed_limit > 0)
865         {
866             *addinfo = "limit";
867             return PAZPAR2_MALFORMED_PARAMETER_VALUE;
868         }
869         else
870             return PAZPAR2_NO_TARGETS;
871     }
872     return PAZPAR2_NO_ERROR;
873 }
874
875 // Creates a new session_database object for a database
876 static void session_init_databases_fun(void *context, struct database *db)
877 {
878     struct session *se = (struct session *) context;
879     struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
880     int i;
881
882     new->database = db;
883
884     new->map = 0;
885     assert(db->settings);
886     new->settings = nmem_malloc(se->session_nmem,
887                                 sizeof(struct settings *) * db->num_settings);
888     new->num_settings = db->num_settings;
889     for (i = 0; i < db->num_settings; i++)
890     {
891         struct setting *setting = db->settings[i];
892         new->settings[i] = setting;
893     }
894     new->next = se->databases;
895     se->databases = new;
896 }
897
898 // Doesn't free memory associated with sdb -- nmem takes care of that
899 static void session_database_destroy(struct session_database *sdb)
900 {
901     sdb->map = 0;
902 }
903
904 // Initialize session_database list -- this represents this session's view
905 // of the database list -- subject to modification by the settings ws command
906 void session_init_databases(struct session *se)
907 {
908     se->databases = 0;
909     predef_grep_databases(se, se->service, session_init_databases_fun);
910 }
911
912 // Probably session_init_databases_fun should be refactored instead of
913 // called here.
914 static struct session_database *load_session_database(struct session *se,
915                                                       const char *id)
916 {
917     struct database *db = new_database_inherit_settings(id, se->session_nmem, se->service->settings);
918     session_init_databases_fun((void*) se, db);
919
920     // New sdb is head of se->databases list
921     return se->databases;
922 }
923
924 // Find an existing session database. If not found, load it
925 static struct session_database *find_session_database(struct session *se,
926                                                       const char *id)
927 {
928     struct session_database *sdb;
929
930     for (sdb = se->databases; sdb; sdb = sdb->next)
931         if (!strcmp(sdb->database->id, id))
932             return sdb;
933     return load_session_database(se, id);
934 }
935
936 // Apply a session override to a database
937 void session_apply_setting(struct session *se, const char *dbname,
938                            const char *name, const char *value)
939 {
940     session_enter(se, "session_apply_setting");
941     {
942         struct session_database *sdb = find_session_database(se, dbname);
943         struct conf_service *service = se->service;
944         struct setting *s;
945         int offset = settings_create_offset(service, name);
946
947         expand_settings_array(&sdb->settings, &sdb->num_settings, offset,
948                               se->session_nmem);
949         // Force later recompute of settings-driven data structures
950         // (happens when a search starts and client connections are prepared)
951         if (offset == PZ_XSLT)
952             sdb->map = 0;
953         se->settings_modified = 1;
954         for (s = sdb->settings[offset]; s; s = s->next)
955             if (!strcmp(s->name, name) &&
956                 dbname && s->target && !strcmp(dbname, s->target))
957                 break;
958         if (!s)
959         {
960             s = nmem_malloc(se->session_nmem, sizeof(*s));
961             s->precedence = 0;
962             s->target = nmem_strdup(se->session_nmem, dbname);
963             s->name = nmem_strdup(se->session_nmem, name);
964             s->next = sdb->settings[offset];
965             sdb->settings[offset] = s;
966         }
967         s->value = nmem_strdup(se->session_nmem, value);
968     }
969     session_leave(se, "session_apply_setting");
970 }
971
972 void session_destroy(struct session *se)
973 {
974     struct session_database *sdb;
975     session_log(se, YLOG_LOG, "destroy");
976     session_use(-1);
977     session_remove_cached_clients(se);
978
979     for (sdb = se->databases; sdb; sdb = sdb->next)
980         session_database_destroy(sdb);
981     normalize_cache_destroy(se->normalize_cache);
982     relevance_destroy(&se->relevance);
983     reclist_destroy(se->reclist);
984     xfree(se->mergekey);
985     xfree(se->rank);
986     if (nmem_total(se->nmem))
987         session_log(se, YLOG_DEBUG, "NMEN operation usage %zd", nmem_total(se->nmem));
988     if (nmem_total(se->session_nmem))
989         session_log(se, YLOG_DEBUG, "NMEN session usage %zd", nmem_total(se->session_nmem));
990     facet_limits_destroy(se->facet_limits);
991     nmem_destroy(se->nmem);
992     service_destroy(se->service);
993     yaz_mutex_destroy(&se->session_mutex);
994 }
995
996 size_t session_get_memory_status(struct session *session) {
997     size_t session_nmem;
998     if (session == 0)
999         return 0;
1000     session_enter(session, "session_get_memory_status");
1001     session_nmem = nmem_total(session->nmem);
1002     session_leave(session, "session_get_memory_status");
1003     return session_nmem;
1004 }
1005
1006
1007 struct session *new_session(NMEM nmem, struct conf_service *service,
1008                             unsigned session_id)
1009 {
1010     int i;
1011     struct session *session = nmem_malloc(nmem, sizeof(*session));
1012
1013     char tmp_str[50];
1014
1015     sprintf(tmp_str, "session#%u", session_id);
1016
1017     session->session_id = session_id;
1018     session_log(session, YLOG_DEBUG, "New");
1019     session->service = service;
1020     session->relevance = 0;
1021     session->total_records = 0;
1022     session->number_of_warnings_unknown_elements = 0;
1023     session->number_of_warnings_unknown_metadata = 0;
1024     session->termlists = 0;
1025     session->reclist = reclist_create(nmem);
1026     session->clients_active = 0;
1027     session->clients_cached = 0;
1028     session->settings_modified = 0;
1029     session->session_nmem = nmem;
1030     session->nmem = nmem_create();
1031     session->databases = 0;
1032     session->sorted_results = 0;
1033     session->facet_limits = 0;
1034     session->mergekey = 0;
1035     session->rank = 0;
1036     session->clients_starting = 0;
1037
1038     for (i = 0; i <= SESSION_WATCH_MAX; i++)
1039     {
1040         session->watchlist[i].data = 0;
1041         session->watchlist[i].fun = 0;
1042     }
1043     session->normalize_cache = normalize_cache_create();
1044     session->session_mutex = 0;
1045     pazpar2_mutex_create(&session->session_mutex, tmp_str);
1046     session_log(session, YLOG_LOG, "create");
1047
1048     session_use(1);
1049     return session;
1050 }
1051
1052 const char * client_get_suggestions_xml(struct client *cl, WRBUF wrbuf);
1053
1054 static struct hitsbytarget *hitsbytarget_nb(struct session *se,
1055                                             int *count, NMEM nmem)
1056 {
1057     struct hitsbytarget *res = 0;
1058     struct client_list *l;
1059     size_t sz = 0;
1060
1061     for (l = se->clients_active; l; l = l->next)
1062         sz++;
1063
1064     res = nmem_malloc(nmem, sizeof(*res) * sz);
1065     *count = 0;
1066     for (l = se->clients_active; l; l = l->next)
1067     {
1068         struct client *cl = l->client;
1069         WRBUF w = wrbuf_alloc();
1070         const char *name = session_setting_oneval(client_get_database(cl),
1071                                                   PZ_NAME);
1072         res[*count].id = client_get_id(cl);
1073         res[*count].name = *name ? name : "Unknown";
1074         res[*count].hits = client_get_hits(cl);
1075         res[*count].approximation = client_get_approximation(cl);
1076         res[*count].records = client_get_num_records(cl,
1077                                                      &res[*count].filtered,
1078                                                      0, 0);
1079         res[*count].diagnostic =
1080             client_get_diagnostic(cl, &res[*count].message,
1081                                   &res[*count].addinfo);
1082         res[*count].state = client_get_state_str(cl);
1083         res[*count].connected  = client_get_connection(cl) ? 1 : 0;
1084         session_settings_dump(se, client_get_database(cl), w);
1085         res[*count].settings_xml = nmem_strdup(nmem, wrbuf_cstr(w));
1086         wrbuf_rewind(w);
1087         wrbuf_puts(w, "");
1088         res[*count].suggestions_xml = nmem_strdup(nmem, client_get_suggestions_xml(cl, w));
1089         wrbuf_destroy(w);
1090         (*count)++;
1091     }
1092     return res;
1093 }
1094
1095 struct hitsbytarget *get_hitsbytarget(struct session *se, int *count, NMEM nmem)
1096 {
1097     struct hitsbytarget *p;
1098     session_enter(se, "get_hitsbytarget");
1099     p = hitsbytarget_nb(se, count, nmem);
1100     session_leave(se, "get_hitsbytarget");
1101     return p;
1102 }
1103
1104 // Compares two hitsbytarget nodes by hitcount
1105 static int cmp_ht(const void *p1, const void *p2)
1106 {
1107     const struct hitsbytarget *h1 = p1;
1108     const struct hitsbytarget *h2 = p2;
1109     return h2->hits - h1->hits;
1110 }
1111
1112 // Compares two hitsbytarget nodes by hitcount
1113 static int cmp_ht_approx(const void *p1, const void *p2)
1114 {
1115     const struct hitsbytarget *h1 = p1;
1116     const struct hitsbytarget *h2 = p2;
1117     return h2->approximation - h1->approximation;
1118 }
1119
1120 static int targets_termlist_nb(WRBUF wrbuf, struct session *se, int num,
1121                                NMEM nmem, int version)
1122 {
1123     struct hitsbytarget *ht;
1124     int count, i;
1125
1126     ht = hitsbytarget_nb(se, &count, nmem);
1127     if (version >= 2)
1128         qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht_approx);
1129     else
1130         qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht);
1131     for (i = 0; i < count && i < num && ht[i].hits > 0; i++)
1132     {
1133
1134         // do only print terms which have display names
1135
1136         wrbuf_puts(wrbuf, "<term>\n");
1137
1138         wrbuf_puts(wrbuf, "<id>");
1139         wrbuf_xmlputs(wrbuf, ht[i].id);
1140         wrbuf_puts(wrbuf, "</id>\n");
1141
1142         wrbuf_puts(wrbuf, "<name>");
1143         if (!ht[i].name || !ht[i].name[0])
1144             wrbuf_xmlputs(wrbuf, "NO TARGET NAME");
1145         else
1146             wrbuf_xmlputs(wrbuf, ht[i].name);
1147         wrbuf_puts(wrbuf, "</name>\n");
1148
1149         wrbuf_printf(wrbuf, "<frequency>" ODR_INT_PRINTF "</frequency>\n",
1150                      ht[i].hits);
1151
1152         if (version >= 2) {
1153             // Should not print if we know it isn't a approximation.
1154             wrbuf_printf(wrbuf, "<approximation>" ODR_INT_PRINTF "</approximation>\n", ht[i].approximation);
1155             wrbuf_printf(wrbuf, "<records>%d</records>\n", ht[i].records - ht[i].filtered);
1156             wrbuf_printf(wrbuf, "<filtered>%d</filtered>\n", ht[i].filtered);
1157         }
1158
1159         wrbuf_puts(wrbuf, "<state>");
1160         wrbuf_xmlputs(wrbuf, ht[i].state);
1161         wrbuf_puts(wrbuf, "</state>\n");
1162
1163         wrbuf_printf(wrbuf, "<diagnostic>%d</diagnostic>\n",
1164                      ht[i].diagnostic);
1165         wrbuf_puts(wrbuf, "</term>\n");
1166     }
1167     return count;
1168 }
1169
1170 void perform_termlist(struct http_channel *c, struct session *se,
1171                       const char *name, int num, int version)
1172 {
1173     int j;
1174     NMEM nmem_tmp = nmem_create();
1175     char **names;
1176     int num_names = 0;
1177
1178     if (!name)
1179         name = "*";
1180
1181     nmem_strsplit(nmem_tmp, ",", name, &names, &num_names);
1182
1183     session_enter(se, "perform_termlist");
1184
1185     for (j = 0; j < num_names; j++)
1186     {
1187         const char *tname;
1188         int must_generate_empty = 1; /* bug 5350 */
1189
1190         struct named_termlist *t = se->termlists;
1191         for (; t; t = t->next)
1192         {
1193             tname = t->name;
1194             if (!strcmp(names[j], tname) || !strcmp(names[j], "*"))
1195             {
1196                 struct termlist_score **p = 0;
1197                 int len;
1198
1199                 wrbuf_puts(c->wrbuf, "<list name=\"");
1200                 wrbuf_xmlputs(c->wrbuf, tname);
1201                 wrbuf_puts(c->wrbuf, "\">\n");
1202                 must_generate_empty = 0;
1203
1204                 p = termlist_highscore(t->termlist, &len, nmem_tmp);
1205                 if (p)
1206                 {
1207                     int i;
1208                     for (i = 0; i < len && i < num; i++)
1209                     {
1210                         // prevent sending empty term elements
1211                         if (!p[i]->display_term || !p[i]->display_term[0])
1212                             continue;
1213
1214                         wrbuf_puts(c->wrbuf, "<term>");
1215                         wrbuf_puts(c->wrbuf, "<name>");
1216                         wrbuf_xmlputs(c->wrbuf, p[i]->display_term);
1217                         wrbuf_puts(c->wrbuf, "</name>");
1218
1219                         wrbuf_printf(c->wrbuf,
1220                                      "<frequency>%d</frequency>",
1221                                      p[i]->frequency);
1222                         wrbuf_puts(c->wrbuf, "</term>\n");
1223                     }
1224                 }
1225                 wrbuf_puts(c->wrbuf, "</list>\n");
1226             }
1227         }
1228         tname = "xtargets";
1229         if (!strcmp(names[j], tname) || !strcmp(names[j], "*"))
1230         {
1231             wrbuf_puts(c->wrbuf, "<list name=\"");
1232             wrbuf_xmlputs(c->wrbuf, tname);
1233             wrbuf_puts(c->wrbuf, "\">\n");
1234
1235             targets_termlist_nb(c->wrbuf, se, num, c->nmem, version);
1236             wrbuf_puts(c->wrbuf, "</list>\n");
1237             must_generate_empty = 0;
1238         }
1239         if (must_generate_empty)
1240         {
1241             wrbuf_puts(c->wrbuf, "<list name=\"");
1242             wrbuf_xmlputs(c->wrbuf, names[j]);
1243             wrbuf_puts(c->wrbuf, "\"/>\n");
1244         }
1245     }
1246     session_leave(se, "perform_termlist");
1247     nmem_destroy(nmem_tmp);
1248 }
1249
1250 #ifdef MISSING_HEADERS
1251 void report_nmem_stats(void)
1252 {
1253     size_t in_use, is_free;
1254
1255     nmem_get_memory_in_use(&in_use);
1256     nmem_get_memory_free(&is_free);
1257
1258     yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1259             (long) in_use, (long) is_free);
1260 }
1261 #endif
1262
1263 struct record_cluster *show_single_start(struct session *se, const char *id,
1264                                          struct record_cluster **prev_r,
1265                                          struct record_cluster **next_r)
1266 {
1267     struct record_cluster *r = 0;
1268
1269     session_enter(se, "show_single_start");
1270     *prev_r = 0;
1271     *next_r = 0;
1272     reclist_limit(se->reclist, se, 1);
1273
1274     reclist_enter(se->reclist);
1275     while ((r = reclist_read_record(se->reclist)))
1276     {
1277         if (!strcmp(r->recid, id))
1278         {
1279             *next_r = reclist_read_record(se->reclist);
1280             break;
1281         }
1282         *prev_r = r;
1283     }
1284     reclist_leave(se->reclist);
1285     if (!r)
1286         session_leave(se, "show_single_start");
1287     return r;
1288 }
1289
1290 void show_single_stop(struct session *se, struct record_cluster *rec)
1291 {
1292     session_leave(se, "show_single_stop");
1293 }
1294
1295
1296 int session_fetch_more(struct session *se)
1297 {
1298     struct client_list *l;
1299     int ret = 0;
1300
1301     for (l = se->clients_active; l; l = l->next)
1302     {
1303         struct client *cl = l->client;
1304         if (client_get_state(cl) == Client_Idle)
1305         {
1306             if (client_fetch_more(cl))
1307             {
1308                 session_log(se, YLOG_LOG, "%s: more to fetch",
1309                             client_get_id(cl));
1310                 ret = 1;
1311             }
1312             else
1313             {
1314                 int filtered;
1315                 int ingest_failures;
1316                 int record_failures;
1317                 int num = client_get_num_records(
1318                     cl, &filtered, &ingest_failures, &record_failures);
1319
1320                 session_log(se, YLOG_LOG, "%s: hits=" ODR_INT_PRINTF
1321                             " fetched=%d filtered=%d",
1322                             client_get_id(cl),
1323                             client_get_hits(cl),
1324                             num, filtered);
1325                 if (ingest_failures || record_failures)
1326                 {
1327                     session_log(se, YLOG_WARN, "%s:"
1328                                 " ingest failures=%d record failures=%d",
1329                                 client_get_id(cl),
1330                                 ingest_failures, record_failures);
1331                 }
1332             }
1333         }
1334         else
1335         {
1336             session_log(se, YLOG_LOG, "%s: no fetch due to state=%s",
1337                         client_get_id(cl), client_get_state_str(cl));
1338         }
1339
1340     }
1341     return ret;
1342 }
1343
1344 struct record_cluster **show_range_start(struct session *se,
1345                                          struct reclist_sortparms *sp,
1346                                          int start, int *num, int *total,
1347                                          Odr_int *sumhits, Odr_int *approx_hits,
1348                                          void (*show_records_ready)(void *data),
1349                                          struct http_channel *chan)
1350 {
1351     struct record_cluster **recs = 0;
1352     struct reclist_sortparms *spp;
1353     struct client_list *l;
1354     int i;
1355 #if USE_TIMING
1356     yaz_timing_t t = yaz_timing_create();
1357 #endif
1358     session_enter(se, "show_range_start");
1359     *sumhits = 0;
1360     *approx_hits = 0;
1361     *total = 0;
1362     reclist_limit(se->reclist, se, 0);
1363     if (se->relevance)
1364     {
1365         for (spp = sp; spp; spp = spp->next)
1366             if (spp->type == Metadata_type_relevance)
1367             {
1368                 relevance_prepare_read(se->relevance, se->reclist);
1369                 break;
1370             }
1371         for (l = se->clients_active; l; l = l->next) {
1372             *sumhits += client_get_hits(l->client);
1373             *approx_hits += client_get_approximation(l->client);
1374         }
1375     }
1376     reclist_sort(se->reclist, sp);
1377
1378     reclist_enter(se->reclist);
1379     *total = reclist_get_num_records(se->reclist);
1380
1381     for (l = se->clients_active; l; l = l->next)
1382         client_update_show_stat(l->client, 0);
1383
1384     for (i = 0; i < start; i++)
1385     {
1386         struct record_cluster *r = reclist_read_record(se->reclist);
1387         if (!r)
1388         {
1389             *num = 0;
1390             break;
1391         }
1392         else
1393         {
1394             struct record *rec = r->records;
1395             for (;rec; rec = rec->next)
1396                 client_update_show_stat(rec->client, 1);
1397         }
1398     }
1399     recs = nmem_malloc(se->nmem, (*num > 0 ? *num : 1) * sizeof(*recs));
1400     for (i = 0; i < *num; i++)
1401     {
1402         struct record_cluster *r = reclist_read_record(se->reclist);
1403         if (!r)
1404         {
1405             *num = i;
1406             break;
1407         }
1408         else
1409         {
1410             struct record *rec = r->records;
1411             for (;rec; rec = rec->next)
1412                 client_update_show_stat(rec->client, 1);
1413             recs[i] = r;
1414         }
1415     }
1416     reclist_leave(se->reclist);
1417 #if USE_TIMING
1418     yaz_timing_stop(t);
1419     session_log(se, YLOG_LOG, "show %6.5f %3.2f %3.2f",
1420             yaz_timing_get_real(t), yaz_timing_get_user(t),
1421             yaz_timing_get_sys(t));
1422     yaz_timing_destroy(&t);
1423 #endif
1424
1425     if (!session_fetch_more(se))
1426         session_log(se, YLOG_LOG, "can not fetch more");
1427     else
1428     {
1429         show_range_stop(se, recs);
1430         session_log(se, YLOG_LOG, "fetching more in progress");
1431         if (session_set_watch(se, SESSION_WATCH_SHOW,
1432                               show_records_ready, chan, chan))
1433         {
1434             session_log(se, YLOG_WARN, "Ignoring show block");
1435             session_enter(se, "show_range_start");
1436         }
1437         else
1438         {
1439             session_log(se, YLOG_LOG, "session watch OK");
1440             return 0;
1441         }
1442     }
1443     return recs;
1444 }
1445
1446 void show_range_stop(struct session *se, struct record_cluster **recs)
1447 {
1448     session_leave(se, "show_range_stop");
1449 }
1450
1451 void statistics(struct session *se, struct statistics *stat)
1452 {
1453     struct client_list *l;
1454     int count = 0;
1455
1456     memset(stat, 0, sizeof(*stat));
1457     stat->num_hits = 0;
1458     for (l = se->clients_active; l; l = l->next)
1459     {
1460         struct client *cl = l->client;
1461         if (!client_get_connection(cl))
1462             stat->num_no_connection++;
1463         stat->num_hits += client_get_hits(cl);
1464         switch (client_get_state(cl))
1465         {
1466         case Client_Connecting: stat->num_connecting++; break;
1467         case Client_Working: stat->num_working++; break;
1468         case Client_Idle: stat->num_idle++; break;
1469         case Client_Failed: stat->num_failed++; break;
1470         case Client_Error: stat->num_error++; break;
1471         default: break;
1472         }
1473         count++;
1474     }
1475     stat->num_records = se->total_records;
1476
1477     stat->num_clients = count;
1478 }
1479
1480 static struct record_metadata *record_metadata_init(
1481     NMEM nmem, const char *value, enum conf_metadata_type type,
1482     struct _xmlAttr *attr)
1483 {
1484     struct record_metadata *rec_md = record_metadata_create(nmem);
1485     struct record_metadata_attr **attrp = &rec_md->attributes;
1486
1487     for (; attr; attr = attr->next)
1488     {
1489         if (attr->children && attr->children->content)
1490         {
1491             if (strcmp((const char *) attr->name, "type")
1492                 && strcmp((const char *) attr->name, "empty"))
1493             {  /* skip the "type" + "empty" attribute..
1494                   The "Type" is already part of the element in output
1495                   (md-%s) and so repeating it here is redundant */
1496                 *attrp = nmem_malloc(nmem, sizeof(**attrp));
1497                 (*attrp)->name =
1498                     nmem_strdup(nmem, (const char *) attr->name);
1499                 (*attrp)->value =
1500                     nmem_strdup(nmem, (const char *) attr->children->content);
1501                 attrp = &(*attrp)->next;
1502             }
1503         }
1504     }
1505     *attrp = 0;
1506
1507     switch (type)
1508     {
1509     case Metadata_type_generic:
1510     case Metadata_type_skiparticle:
1511         if (strstr(value, "://")) /* looks like a URL */
1512             rec_md->data.text.disp = nmem_strdup(nmem, value);
1513         else
1514             rec_md->data.text.disp =
1515                 normalize7bit_generic(nmem_strdup(nmem, value), " ,/.:([");
1516         rec_md->data.text.sort = 0;
1517         rec_md->data.text.snippet = 0;
1518         break;
1519     case Metadata_type_year:
1520     case Metadata_type_date:
1521     {
1522         int first, last;
1523         int longdate = 0;
1524
1525         if (type == Metadata_type_date)
1526             longdate = 1;
1527         if (extract7bit_dates((char *) value, &first, &last, longdate) < 0)
1528             return 0;
1529
1530         rec_md->data.number.min = first;
1531         rec_md->data.number.max = last;
1532     }
1533     break;
1534     case Metadata_type_float:
1535         rec_md->data.fnumber = atof(value);
1536         break;
1537     case Metadata_type_relevance:
1538     case Metadata_type_position:
1539         return 0;
1540     }
1541     return rec_md;
1542 }
1543
1544 static void mergekey_norm_wr(pp2_charset_fact_t charsets,
1545                              WRBUF norm_wr, const char *value)
1546 {
1547     const char *norm_str;
1548     pp2_charset_token_t prt =
1549         pp2_charset_token_create(charsets, "mergekey");
1550
1551     pp2_charset_token_first(prt, value, 0);
1552     while ((norm_str = pp2_charset_token_next(prt)))
1553     {
1554         if (*norm_str)
1555         {
1556             if (wrbuf_len(norm_wr))
1557                 wrbuf_puts(norm_wr, " ");
1558             wrbuf_puts(norm_wr, norm_str);
1559         }
1560     }
1561     pp2_charset_token_destroy(prt);
1562 }
1563
1564 static int get_mergekey_from_doc(xmlDoc *doc, xmlNode *root, const char *name,
1565                                  struct conf_service *service, WRBUF norm_wr)
1566 {
1567     xmlNode *n;
1568     int no_found = 0;
1569     for (n = root->children; n; n = n->next)
1570     {
1571         if (n->type != XML_ELEMENT_NODE)
1572             continue;
1573         if (!strcmp((const char *) n->name, "metadata"))
1574         {
1575             const char *type = yaz_xml_get_prop(n, "type");
1576             if (type == NULL) {
1577                 yaz_log(YLOG_FATAL, "Missing type attribute on metadata element. Skipping!");
1578             }
1579             else if (!strcmp(name, (const char *) type))
1580             {
1581                 xmlChar *value = xmlNodeListGetString(doc, n->children, 1);
1582                 if (value && *value)
1583                 {
1584                     if (wrbuf_len(norm_wr) > 0)
1585                         wrbuf_puts(norm_wr, " ");
1586                     wrbuf_puts(norm_wr, name);
1587                     mergekey_norm_wr(service->charsets, norm_wr,
1588                                      (const char *) value);
1589                     no_found++;
1590                 }
1591                 if (value)
1592                     xmlFree(value);
1593             }
1594         }
1595     }
1596     return no_found;
1597 }
1598
1599 static const char *get_mergekey(xmlDoc *doc, xmlNode *root, 
1600                                 struct client *cl, int record_no,
1601                                 struct conf_service *service, NMEM nmem,
1602                                 const char *session_mergekey)
1603 {
1604     char *mergekey_norm = 0;
1605     WRBUF norm_wr = wrbuf_alloc();
1606     const char *mergekey;
1607
1608     if (session_mergekey)
1609     {
1610         int i, num = 0;
1611         char **values = 0;
1612         nmem_strsplit_escape2(nmem, ",", session_mergekey, &values,
1613                               &num, 1, '\\', 1);
1614
1615         for (i = 0; i < num; i++)
1616             get_mergekey_from_doc(doc, root, values[i], service, norm_wr);
1617     }
1618     else if ((mergekey = yaz_xml_get_prop(root, "mergekey")))
1619     {
1620         mergekey_norm_wr(service->charsets, norm_wr, mergekey);
1621     }
1622     else
1623     {
1624         /* no mergekey defined in XSL. Look for mergekey metadata instead */
1625         int field_id;
1626         for (field_id = 0; field_id < service->num_metadata; field_id++)
1627         {
1628             struct conf_metadata *ser_md = &service->metadata[field_id];
1629             if (ser_md->mergekey != Metadata_mergekey_no)
1630             {
1631                 int r = get_mergekey_from_doc(doc, root, ser_md->name,
1632                                               service, norm_wr);
1633                 if (r == 0 && ser_md->mergekey == Metadata_mergekey_required)
1634                 {
1635                     /* no mergekey on this one and it is required..
1636                        Generate unique key instead */
1637                     wrbuf_rewind(norm_wr);
1638                     break;
1639                 }
1640             }
1641         }
1642     }
1643
1644     /* generate unique key if none is not generated already or is empty */
1645     if (wrbuf_len(norm_wr) == 0)
1646     {
1647         wrbuf_printf(norm_wr, "position: %s-%d",
1648                      client_get_id(cl), record_no);
1649     }
1650     else
1651     {
1652         const char *lead = "content: ";
1653         wrbuf_insert(norm_wr, 0, lead, strlen(lead));
1654     }
1655     if (wrbuf_len(norm_wr) > 0)
1656         mergekey_norm = nmem_strdup(nmem, wrbuf_cstr(norm_wr));
1657     wrbuf_destroy(norm_wr);
1658     return mergekey_norm;
1659 }
1660
1661 /** \brief see if metadata for pz:recordfilter exists
1662     \param root xml root element of normalized record
1663     \param sdb session database for client
1664     \retval 0 if there is no metadata for pz:recordfilter
1665     \retval 1 if there is metadata for pz:recordfilter
1666
1667     If there is no pz:recordfilter defined, this function returns 1
1668     as well.
1669 */
1670
1671 static int check_record_filter(xmlNode *root, struct session_database *sdb)
1672 {
1673     int match = 0;
1674     xmlNode *n;
1675     const char *s;
1676     s = session_setting_oneval(sdb, PZ_RECORDFILTER);
1677
1678     if (!s || !*s)
1679         return 1;
1680
1681     for (n = root->children; n; n = n->next)
1682     {
1683         if (n->type != XML_ELEMENT_NODE)
1684             continue;
1685         if (!strcmp((const char *) n->name, "metadata"))
1686         {
1687             const char *type = yaz_xml_get_prop(n, "type");
1688             if (type)
1689             {
1690                 size_t len;
1691                 int substring;
1692                 const char *eq;
1693
1694                 if ((eq = strchr(s, '=')))
1695                     substring = 0;
1696                 else if ((eq = strchr(s, '~')))
1697                     substring = 1;
1698                 if (eq)
1699                     len = eq - s;
1700                 else
1701                     len = strlen(s);
1702                 if (len == strlen((const char *)type) &&
1703                     !memcmp((const char *) type, s, len))
1704                 {
1705                     xmlChar *value = xmlNodeGetContent(n);
1706                     if (value && *value)
1707                     {
1708                         if (!eq ||
1709                             (substring && strstr((const char *) value, eq+1)) ||
1710                             (!substring && !strcmp((const char *) value, eq + 1)))
1711                             match = 1;
1712                     }
1713                     xmlFree(value);
1714                 }
1715             }
1716         }
1717     }
1718     return match;
1719 }
1720
1721 static int ingest_to_cluster(struct client *cl,
1722                              WRBUF wrbuf_disp,
1723                              WRBUF wrbuf_norm,
1724                              xmlDoc *xdoc,
1725                              xmlNode *root,
1726                              int record_no,
1727                              struct record_metadata_attr *mergekey);
1728
1729 static int ingest_sub_record(struct client *cl, xmlDoc *xdoc, xmlNode *root,
1730                              int record_no, NMEM nmem,
1731                              struct session_database *sdb,
1732                              struct record_metadata_attr *mergekeys)
1733 {
1734     int ret = 0;
1735     struct session *se = client_get_session(cl);
1736     WRBUF wrbuf_disp, wrbuf_norm;
1737
1738     if (!check_record_filter(root, sdb))
1739     {
1740         session_log(se, YLOG_LOG,
1741                     "Filtered out record no %d from %s",
1742                     record_no, sdb->database->id);
1743         return 0;
1744     }
1745     wrbuf_disp = wrbuf_alloc();
1746     wrbuf_norm = wrbuf_alloc();
1747     session_enter(se, "ingest_sub_record");
1748     if (client_get_session(cl) == se && se->relevance)
1749         ret = ingest_to_cluster(cl, wrbuf_disp, wrbuf_norm,
1750                                 xdoc, root, record_no, mergekeys);
1751     session_leave(se, "ingest_sub_record");
1752     wrbuf_destroy(wrbuf_norm);
1753     wrbuf_destroy(wrbuf_disp);
1754     return ret;
1755 }
1756
1757 /** \brief ingest XML record
1758     \param cl client holds the result set for record
1759     \param rec record buffer (0 terminated)
1760     \param record_no record position (1, 2, ..)
1761     \param nmem working NMEM
1762     \retval 0 OK
1763     \retval -1 failure
1764     \retval -2 Filtered
1765 */
1766 int ingest_record(struct client *cl, const char *rec,
1767                   int record_no, NMEM nmem)
1768 {
1769     struct session *se = client_get_session(cl);
1770     struct session_database *sdb = client_get_database(cl);
1771     struct conf_service *service = se->service;
1772     xmlDoc *xdoc = normalize_record(se, sdb, service, rec, nmem);
1773     int r = ingest_xml_record(cl, xdoc, record_no, nmem, 0);
1774     client_store_xdoc(cl, record_no, xdoc);
1775     return r;
1776 }
1777
1778 int ingest_xml_record(struct client *cl, xmlDoc *xdoc,
1779                       int record_no, NMEM nmem, int cached_copy)
1780 {
1781     struct session *se = client_get_session(cl);
1782     struct session_database *sdb = client_get_database(cl);
1783     struct conf_service *service = se->service;
1784     xmlNode *root;
1785     int r = 0;
1786     if (!xdoc)
1787         return -1;
1788
1789     if (global_parameters.dump_records)
1790     {
1791         session_log(se, YLOG_LOG, "Normalized record from %s",
1792                     sdb->database->id);
1793         log_xml_doc(xdoc);
1794     }
1795
1796     root = xmlDocGetRootElement(xdoc);
1797
1798     if (!strcmp((const char *) root->name, "cluster"))
1799     {
1800         int no_merge_keys = 0;
1801         int no_merge_dups = 0;
1802         xmlNode *sroot;
1803         struct record_metadata_attr *mk = 0;
1804
1805         for (sroot = root->children; sroot; sroot = sroot->next)
1806             if (sroot->type == XML_ELEMENT_NODE &&
1807                 !strcmp((const char *) sroot->name, "record"))
1808             {
1809                 struct record_metadata_attr **mkp;
1810                 const char *mergekey_norm =
1811                     get_mergekey(xdoc, sroot, cl, record_no, service, nmem,
1812                                  se->mergekey);
1813                 if (!mergekey_norm)
1814                 {
1815                     r = -1;
1816                     break;
1817                 }
1818                 for (mkp = &mk; *mkp; mkp = &(*mkp)->next)
1819                     if (!strcmp((*mkp)->value, mergekey_norm))
1820                         break;
1821                 if (!*mkp)
1822                 {
1823                     *mkp = (struct record_metadata_attr*)
1824                         nmem_malloc(nmem, sizeof(**mkp));
1825                     (*mkp)->name = 0;
1826                     (*mkp)->value = nmem_strdup(nmem, mergekey_norm);
1827                     (*mkp)->next = 0;
1828                     no_merge_keys++;
1829                 }
1830                 else
1831                     no_merge_dups++;
1832             }
1833         if (no_merge_keys > 1 || no_merge_dups > 0)
1834         {
1835             yaz_log(YLOG_LOG, "Got %d mergekeys, %d dups for position %d",
1836                     no_merge_keys, no_merge_dups, record_no);
1837         }
1838         for (sroot = root->children; !r && sroot; sroot = sroot->next)
1839             if (sroot->type == XML_ELEMENT_NODE &&
1840                 !strcmp((const char *) sroot->name, "record"))
1841             {
1842                 if (!cached_copy)
1843                     insert_settings_values(sdb, xdoc, root, service);
1844                 r = ingest_sub_record(cl, xdoc, sroot, record_no, nmem, sdb,
1845                                       mk);
1846             }
1847     }
1848     else if (!strcmp((const char *) root->name, "record"))
1849     {
1850         const char *mergekey_norm =
1851             get_mergekey(xdoc, root, cl, record_no, service, nmem,
1852                          se->mergekey);
1853         if (mergekey_norm)
1854         {
1855             struct record_metadata_attr *mk = (struct record_metadata_attr*)
1856                 nmem_malloc(nmem, sizeof(*mk));
1857             mk->name = 0;
1858             mk->value = nmem_strdup(nmem, mergekey_norm);
1859             mk->next = 0;
1860
1861             if (!cached_copy)
1862                 insert_settings_values(sdb, xdoc, root, service);
1863             r = ingest_sub_record(cl, xdoc, root, record_no, nmem, sdb, mk);
1864         }
1865     }
1866     else
1867     {
1868         session_log(se, YLOG_WARN, "Bad pz root element: %s",
1869                     (const char *) root->name);
1870         r = -1;
1871     }
1872     return r;
1873 }
1874
1875
1876 //    struct conf_metadata *ser_md = &service->metadata[md_field_id];
1877 //    struct record_metadata *rec_md = record->metadata[md_field_id];
1878 static int match_metadata_local(struct conf_service *service,
1879                                 struct conf_metadata *ser_md,
1880                                 struct record_metadata *rec_md0,
1881                                 char **values, int num_v)
1882 {
1883     int i;
1884     struct record_metadata *rec_md = rec_md0;
1885     WRBUF val_wr = 0;
1886     WRBUF text_wr = wrbuf_alloc();
1887     for (i = 0; i < num_v; )
1888     {
1889         if (rec_md)
1890         {
1891             if (ser_md->type == Metadata_type_year
1892                 || ser_md->type == Metadata_type_date)
1893             {
1894                 int y = atoi(values[i]);
1895                 if (y >= rec_md->data.number.min
1896                     && y <= rec_md->data.number.max)
1897                     break;
1898             }
1899             else
1900             {
1901                 if (!val_wr)
1902                 {
1903                     val_wr = wrbuf_alloc();
1904                     mergekey_norm_wr(service->charsets, val_wr, values[i]);
1905                 }
1906                 wrbuf_rewind(text_wr);
1907                 mergekey_norm_wr(service->charsets, text_wr,
1908                                  rec_md->data.text.disp);
1909                 if (!strcmp(wrbuf_cstr(val_wr), wrbuf_cstr(text_wr)))
1910                     break;
1911             }
1912             rec_md = rec_md->next;
1913         }
1914         else
1915         {
1916             rec_md = rec_md0;
1917             wrbuf_destroy(val_wr);
1918             val_wr = 0;
1919             i++;
1920         }
1921     }
1922     wrbuf_destroy(val_wr);
1923     wrbuf_destroy(text_wr);
1924     return i < num_v ? 1 : 0;
1925 }
1926
1927 int session_check_cluster_limit(struct session *se, struct record_cluster *rec)
1928 {
1929     int i;
1930     struct conf_service *service = se->service;
1931     int ret = 1;
1932     const char *name;
1933     const char *value;
1934     NMEM nmem_tmp = nmem_create();
1935
1936     for (i = 0; (name = facet_limits_get(se->facet_limits, i, &value)); i++)
1937     {
1938         int j;
1939         for (j = 0; j < service->num_metadata; j++)
1940         {
1941             struct conf_metadata *md = service->metadata + j;
1942             if (!strcmp(md->name, name) && md->limitcluster)
1943             {
1944                 char **values = 0;
1945                 int num = 0;
1946                 int md_field_id =
1947                     conf_service_metadata_field_id(service,
1948                                                    md->limitcluster);
1949
1950                 if (md_field_id < 0)
1951                 {
1952                     ret = 0;
1953                     break;
1954                 }
1955
1956                 nmem_strsplit_escape2(nmem_tmp, "|", value, &values,
1957                                       &num, 1, '\\', 1);
1958
1959                 if (!match_metadata_local(service,
1960                                           &service->metadata[md_field_id],
1961                                           rec->metadata[md_field_id],
1962                                           values, num))
1963                 {
1964                     ret = 0;
1965                     break;
1966                 }
1967             }
1968         }
1969     }
1970     nmem_destroy(nmem_tmp);
1971     return ret;
1972 }
1973
1974 // Skip record on non-zero
1975 static int check_limit_local(struct client *cl,
1976                              struct record *record,
1977                              int record_no)
1978 {
1979     int skip_record = 0;
1980     struct session *se = client_get_session(cl);
1981     struct conf_service *service = se->service;
1982     NMEM nmem_tmp = nmem_create();
1983     struct session_database *sdb = client_get_database(cl);
1984     int l = 0;
1985     while (!skip_record)
1986     {
1987         int md_field_id;
1988         char **values = 0;
1989         int num_v = 0;
1990         const char *name =
1991             client_get_facet_limit_local(cl, sdb, &l, nmem_tmp,
1992                                          &num_v, &values);
1993         if (!name)
1994             break;
1995
1996         if (!strcmp(name, "*"))
1997         {
1998             for (md_field_id = 0; md_field_id < service->num_metadata;
1999                  md_field_id++)
2000             {
2001                 if (match_metadata_local(
2002                         service,
2003                         &service->metadata[md_field_id],
2004                         record->metadata[md_field_id],
2005                         values, num_v))
2006                     break;
2007             }
2008             if (md_field_id == service->num_metadata)
2009                 skip_record = 1;
2010         }
2011         else
2012         {
2013             md_field_id = conf_service_metadata_field_id(service, name);
2014             if (md_field_id < 0)
2015             {
2016                 skip_record = 1;
2017                 break;
2018             }
2019             if (!match_metadata_local(
2020                     service,
2021                     &service->metadata[md_field_id],
2022                     record->metadata[md_field_id],
2023                     values, num_v))
2024             {
2025                 skip_record = 1;
2026             }
2027         }
2028     }
2029     nmem_destroy(nmem_tmp);
2030     return skip_record;
2031 }
2032
2033 static int ingest_to_cluster(struct client *cl,
2034                              WRBUF wrbuf_disp,
2035                              WRBUF wrbuf_norm,
2036                              xmlDoc *xdoc,
2037                              xmlNode *root,
2038                              int record_no,
2039                              struct record_metadata_attr *merge_keys)
2040 {
2041     xmlNode *n;
2042     struct session *se = client_get_session(cl);
2043     struct conf_service *service = se->service;
2044     int term_factor = 1;
2045     struct record_cluster *cluster;
2046     struct record_metadata **metadata0;
2047     struct session_database *sdb = client_get_database(cl);
2048     NMEM ingest_nmem = 0;
2049     char **rank_values = 0;
2050     int rank_num = 0;
2051     struct record *record = record_create(se->nmem,
2052                                           service->num_metadata,
2053                                           service->num_sortkeys, cl,
2054                                           record_no);
2055
2056     for (n = root->children; n; n = n->next)
2057     {
2058         if (n->type != XML_ELEMENT_NODE)
2059             continue;
2060         if (!strcmp((const char *) n->name, "metadata"))
2061         {
2062             struct conf_metadata *ser_md = 0;
2063             struct record_metadata **wheretoput = 0;
2064             struct record_metadata *rec_md = 0;
2065             int md_field_id = -1;
2066             xmlChar *value0;
2067             const char *type = yaz_xml_get_prop(n, "type");
2068
2069             if (!type)
2070                 continue;
2071             wrbuf_rewind(wrbuf_disp);
2072             value0 = xmlNodeListGetString(xdoc, n->children, 1);
2073             if (!value0 || !*value0)
2074             {
2075                 const char *empty = yaz_xml_get_prop(n, "empty");
2076                 if (!empty)
2077                     continue;
2078                 wrbuf_puts(wrbuf_disp, (const char *) empty);
2079             }
2080             else
2081             {
2082                 wrbuf_puts(wrbuf_disp, (const char *) value0);
2083             }
2084             if (value0)
2085                 xmlFree(value0);
2086             md_field_id
2087                 = conf_service_metadata_field_id(service, (const char *) type);
2088             if (md_field_id < 0)
2089             {
2090                 if (se->number_of_warnings_unknown_metadata == 0)
2091                 {
2092                     session_log(se, YLOG_WARN,
2093                             "Ignoring unknown metadata element: %s", type);
2094                 }
2095                 se->number_of_warnings_unknown_metadata++;
2096                 continue;
2097             }
2098
2099             ser_md = &service->metadata[md_field_id];
2100
2101             // non-merged metadata
2102             rec_md = record_metadata_init(se->nmem, wrbuf_cstr(wrbuf_disp),
2103                                           ser_md->type, n->properties);
2104             if (!rec_md)
2105             {
2106                 session_log(se, YLOG_WARN, "bad metadata data '%s' "
2107                             "for element '%s'", wrbuf_cstr(wrbuf_disp), type);
2108                 continue;
2109             }
2110
2111             if (ser_md->type == Metadata_type_generic)
2112             {
2113                 WRBUF w = wrbuf_alloc();
2114                 if (relevance_snippet(se->relevance,
2115                                       wrbuf_cstr(wrbuf_disp), ser_md->name, w))
2116                     rec_md->data.text.snippet = nmem_strdup(se->nmem,
2117                                                             wrbuf_cstr(w));
2118                 wrbuf_destroy(w);
2119             }
2120
2121
2122             wheretoput = &record->metadata[md_field_id];
2123             while (*wheretoput)
2124                 wheretoput = &(*wheretoput)->next;
2125             *wheretoput = rec_md;
2126         }
2127     }
2128
2129     if (check_limit_local(cl, record, record_no))
2130     {
2131         return -2;
2132     }
2133     cluster = reclist_insert(se->reclist, se->relevance, service, record,
2134                              merge_keys, &se->total_merged);
2135     if (!cluster)
2136     {
2137         return 0; // complete match with existing record
2138     }
2139
2140     {
2141         const char *use_term_factor_str =
2142             session_setting_oneval(sdb, PZ_TERMLIST_TERM_FACTOR);
2143         if (use_term_factor_str && use_term_factor_str[0] == '1')
2144         {
2145             int maxrecs = client_get_maxrecs(cl);
2146             int hits = (int) client_get_hits(cl);
2147             term_factor = MAX(hits, maxrecs) /  MAX(1, maxrecs);
2148             assert(term_factor >= 1);
2149             session_log(se, YLOG_DEBUG, "Using term factor: %d (%d / %d)",
2150                         term_factor, MAX(hits, maxrecs), MAX(1, maxrecs));
2151         }
2152     }
2153
2154     if (global_parameters.dump_records)
2155         session_log(se, YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
2156                     sdb->database->id, record_no);
2157
2158     // original metadata, to check if first existence of a field
2159     metadata0 = xmalloc(sizeof(*metadata0) * service->num_metadata);
2160     memcpy(metadata0, cluster->metadata,
2161            sizeof(*metadata0) * service->num_metadata);
2162
2163     ingest_nmem = nmem_create();
2164     if (se->rank)
2165     {
2166         yaz_log(YLOG_LOG, "local in sort : %s", se->rank);
2167         nmem_strsplit_escape2(ingest_nmem, ",", se->rank, &rank_values,
2168                               &rank_num, 1, '\\', 1);
2169     }
2170
2171     // now parsing XML record and adding data to cluster or record metadata
2172     for (n = root->children; n; n = n->next)
2173     {
2174         if (n->type != XML_ELEMENT_NODE)
2175             continue;
2176         if (!strcmp((const char *) n->name, "metadata"))
2177         {
2178             struct conf_metadata *ser_md = 0;
2179             struct conf_sortkey *ser_sk = 0;
2180             struct record_metadata **wheretoput = 0;
2181             struct record_metadata *rec_md = 0;
2182             int md_field_id = -1;
2183             int sk_field_id = -1;
2184             const char *rank = 0;
2185             const char *xml_rank = 0;
2186             const char *type = 0;
2187             xmlChar *value0;
2188
2189             wrbuf_rewind(wrbuf_disp);
2190             type = yaz_xml_get_prop(n, "type");
2191             if (!type)
2192                 continue;
2193
2194             md_field_id
2195                 = conf_service_metadata_field_id(service, (const char *) type);
2196             if (md_field_id < 0)
2197                 continue;
2198
2199             ser_md = &service->metadata[md_field_id];
2200
2201             if (ser_md->sortkey_offset >= 0)
2202             {
2203                 sk_field_id = ser_md->sortkey_offset;
2204                 ser_sk = &service->sortkeys[sk_field_id];
2205             }
2206
2207             value0 = xmlNodeListGetString(xdoc, n->children, 1);
2208             if (!value0 || !*value0)
2209             {
2210                 if (value0)
2211                     xmlFree(value0);
2212                 continue;
2213             }
2214             wrbuf_puts(wrbuf_disp, (const char *) value0);
2215             xmlFree(value0);
2216
2217
2218             // merged metadata
2219             rec_md = record_metadata_init(se->nmem, wrbuf_cstr(wrbuf_disp),
2220                                           ser_md->type, 0);
2221
2222             // see if the field was not in cluster already (from beginning)
2223
2224             if (!rec_md)
2225                 continue;
2226
2227             if (rank_num)
2228             {
2229                 int i;
2230                 for (i = 0; i < rank_num; i++)
2231                 {
2232                     const char *val = rank_values[i];
2233                     const char *cp = strchr(val, '=');
2234                     if (!cp)
2235                         continue;
2236                     if ((cp - val) == strlen((const char *) type)
2237                         && !memcmp(val, type, cp - val))
2238                     {
2239                         rank = cp + 1;
2240                         break;
2241                     }
2242                 }
2243             }
2244             else
2245             {
2246                 xml_rank = yaz_xml_get_prop(n, "rank");
2247                 rank = xml_rank ? (const char *) xml_rank : ser_md->rank;
2248             }
2249
2250             wheretoput = &cluster->metadata[md_field_id];
2251
2252             if (ser_md->merge == Metadata_merge_first)
2253             {
2254                 if (!metadata0[md_field_id])
2255                 {
2256                     while (*wheretoput)
2257                         wheretoput = &(*wheretoput)->next;
2258                     *wheretoput = rec_md;
2259                 }
2260             }
2261             else if (ser_md->merge == Metadata_merge_unique)
2262             {
2263                 while (*wheretoput)
2264                 {
2265                     if (!strcmp((const char *) (*wheretoput)->data.text.disp,
2266                                 rec_md->data.text.disp))
2267                         break;
2268                     wheretoput = &(*wheretoput)->next;
2269                 }
2270                 if (!*wheretoput)
2271                     *wheretoput = rec_md;
2272             }
2273             else if (ser_md->merge == Metadata_merge_longest)
2274             {
2275                 if (!*wheretoput
2276                     || strlen(rec_md->data.text.disp)
2277                     > strlen((*wheretoput)->data.text.disp))
2278                 {
2279                     *wheretoput = rec_md;
2280                     if (ser_sk)
2281                     {
2282                         pp2_charset_token_t prt;
2283                         const char *sort_str = 0;
2284                         int skip_article =
2285                             ser_sk->type == Metadata_type_skiparticle;
2286
2287                         if (!cluster->sortkeys[sk_field_id])
2288                             cluster->sortkeys[sk_field_id] =
2289                                 nmem_malloc(se->nmem,
2290                                             sizeof(union data_types));
2291
2292                         prt =
2293                             pp2_charset_token_create(service->charsets, "sort");
2294
2295                         pp2_charset_token_first(prt, rec_md->data.text.disp,
2296                                                 skip_article);
2297
2298                         pp2_charset_token_next(prt);
2299
2300                         sort_str = pp2_get_sort(prt);
2301
2302                         cluster->sortkeys[sk_field_id]->text.disp =
2303                             rec_md->data.text.disp;
2304                         if (!sort_str)
2305                         {
2306                             sort_str = rec_md->data.text.disp;
2307                             session_log(se, YLOG_WARN,
2308                                     "Could not make sortkey. Bug #1858");
2309                         }
2310                         cluster->sortkeys[sk_field_id]->text.sort =
2311                             nmem_strdup(se->nmem, sort_str);
2312                         pp2_charset_token_destroy(prt);
2313                     }
2314                 }
2315             }
2316             else if (ser_md->merge == Metadata_merge_all)
2317             {
2318                 while (*wheretoput)
2319                     wheretoput = &(*wheretoput)->next;
2320                 *wheretoput = rec_md;
2321             }
2322             else if (ser_md->merge == Metadata_merge_range)
2323             {
2324                 if (!*wheretoput)
2325                 {
2326                     *wheretoput = rec_md;
2327                     if (ser_sk)
2328                         cluster->sortkeys[sk_field_id]
2329                             = &rec_md->data;
2330                 }
2331                 else
2332                 {
2333                     int this_min = rec_md->data.number.min;
2334                     int this_max = rec_md->data.number.max;
2335                     if (this_min < (*wheretoput)->data.number.min)
2336                         (*wheretoput)->data.number.min = this_min;
2337                     if (this_max > (*wheretoput)->data.number.max)
2338                         (*wheretoput)->data.number.max = this_max;
2339                 }
2340             }
2341
2342             // ranking of _all_ fields enabled ...
2343             if (rank)
2344             {
2345                 relevance_countwords(se->relevance, cluster,
2346                                      wrbuf_cstr(wrbuf_disp),
2347                                      rank, ser_md->name);
2348             }
2349             // construct facets ... unless the client already has reported them
2350             if (ser_md->termlist && !client_has_facet(cl, (char *) type))
2351             {
2352                 if (ser_md->type == Metadata_type_year)
2353                 {
2354                     char year[64];
2355                     sprintf(year, "%d", rec_md->data.number.max);
2356
2357                     add_facet(se, (char *) type, year, term_factor);
2358                     if (rec_md->data.number.max != rec_md->data.number.min)
2359                     {
2360                         sprintf(year, "%d", rec_md->data.number.min);
2361                         add_facet(se, (char *) type, year, term_factor);
2362                     }
2363                 }
2364                 else
2365                     add_facet(se, type, wrbuf_cstr(wrbuf_disp), term_factor);
2366             }
2367         }
2368         else
2369         {
2370             if (se->number_of_warnings_unknown_elements == 0)
2371                 session_log(se, YLOG_WARN,
2372                         "Unexpected element in internal record: %s", n->name);
2373             se->number_of_warnings_unknown_elements++;
2374         }
2375     }
2376     nmem_destroy(ingest_nmem);
2377     xfree(metadata0);
2378     relevance_donerecord(se->relevance, cluster);
2379     se->total_records++;
2380
2381     return 0;
2382 }
2383
2384 void session_log(struct session *s, int level, const char *fmt, ...)
2385 {
2386     char buf[1024];
2387     va_list ap;
2388     va_start(ap, fmt);
2389
2390     yaz_vsnprintf(buf, sizeof(buf)-30, fmt, ap);
2391     yaz_log(level, "Session %u: %s", s ? s->session_id : 0, buf);
2392
2393     va_end(ap);
2394 }
2395
2396 /*
2397  * Local variables:
2398  * c-basic-offset: 4
2399  * c-file-style: "Stroustrup"
2400  * indent-tabs-mode: nil
2401  * End:
2402  * vim: shiftwidth=4 tabstop=8 expandtab
2403  */
2404