a294c8e4f07d19008138540390cd53111056da04
[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 struct facet_id {
207     char *client_id;
208     char *type;
209     char *id;
210     char *term;
211     struct facet_id *next;
212 };
213
214 static void session_add_id_facet(struct session *s, struct client *cl,
215                                  const char *type,
216                                  const char *id,
217                                  size_t id_len,
218                                  const char *term)
219 {
220     struct facet_id *t = nmem_malloc(s->session_nmem, sizeof(*t));
221
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;
228 }
229
230
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,
235                                     const char *type,
236                                     const char *term)
237 {
238     char *retval = 0;
239     struct facet_id *t = s->facet_id_list;
240     for (; t; t = t->next) 
241     {
242         if (!strcmp(client_get_id(cl), t->client_id) &&  !strcmp(t->type, type) )
243         {
244             retval = "";
245             if ( !strcmp(t->term, term))
246             {
247                 return t->id;
248             }
249         }
250     }
251     return retval;
252 }
253
254 void add_facet(struct session *s, const char *type, const char *value, int count, struct client *cl)
255 {
256     WRBUF facet_wrbuf = wrbuf_alloc();
257     WRBUF display_wrbuf = wrbuf_alloc();
258     const char *id = 0;
259     size_t id_len = 0;
260
261     /* inspect pz:facetmap:split:name ?? */
262     if (!strncmp(type, "split:", 6))
263     {
264         const char *cp = strchr(value, ':');
265         if (cp)
266         {
267             id = value;
268             id_len = cp - value;
269             value = cp + 1;
270         }
271         type += 6;
272     }
273
274     session_normalize_facet(s, type, value, display_wrbuf, facet_wrbuf);
275     if (wrbuf_len(facet_wrbuf))
276     {
277         struct named_termlist **tp = &s->termlists;
278         for (; (*tp); tp = &(*tp)->next)
279             if (!strcmp((*tp)->name, type))
280                 break;
281         if (!*tp)
282         {
283             *tp = nmem_malloc(s->nmem, sizeof(**tp));
284             (*tp)->name = nmem_strdup(s->nmem, type);
285             (*tp)->termlist = termlist_create(s->nmem);
286             (*tp)->next = 0;
287         }
288         termlist_insert((*tp)->termlist, wrbuf_cstr(display_wrbuf),
289                         wrbuf_cstr(facet_wrbuf), id, id_len, count);
290         if (id)
291             session_add_id_facet(s, cl, type, id, id_len,
292                                  wrbuf_cstr(display_wrbuf));
293     }
294     wrbuf_destroy(facet_wrbuf);
295     wrbuf_destroy(display_wrbuf);
296 }
297
298 static xmlDoc *record_to_xml(struct session *se,
299                              struct session_database *sdb, const char *rec)
300 {
301     struct database *db = sdb->database;
302     xmlDoc *rdoc = 0;
303
304     rdoc = xmlParseMemory(rec, strlen(rec));
305
306     if (!rdoc)
307     {
308         session_log(se, YLOG_WARN, "Non-wellformed XML");
309         return 0;
310     }
311
312     if (global_parameters.dump_records)
313     {
314         session_log(se, YLOG_LOG, "Un-normalized record from %s", db->id);
315         log_xml_doc(rdoc);
316     }
317
318     return rdoc;
319 }
320
321 #define MAX_XSLT_ARGS 16
322
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,
326                                        char **parms,
327                                        NMEM nmem)
328 {
329     int i;
330     int nparms = 0;
331     int offset = 0;
332
333     for (i = 0; i < service->num_metadata; i++)
334     {
335         struct conf_metadata *md = &service->metadata[i];
336         int setting;
337
338         if (md->setting == Metadata_setting_parameter &&
339             (setting = settings_lookup_offset(service, md->name)) >= 0)
340         {
341             const char *val = session_setting_oneval(sdb, setting);
342             if (val && nparms < MAX_XSLT_ARGS)
343             {
344                 char *buf;
345                 int len = strlen(val);
346                 buf = nmem_malloc(nmem, len + 3);
347                 buf[0] = '\'';
348                 strcpy(buf + 1, val);
349                 buf[len+1] = '\'';
350                 buf[len+2] = '\0';
351                 parms[offset++] = md->name;
352                 parms[offset++] = buf;
353                 nparms++;
354             }
355         }
356     }
357     parms[offset] = 0;
358 }
359
360 // Add static values from session database settings if applicable
361 static void insert_settings_values(struct session_database *sdb, xmlDoc *doc,
362                                    xmlNode *root,
363                                    struct conf_service *service)
364 {
365     int i;
366
367     for (i = 0; i < service->num_metadata; i++)
368     {
369         struct conf_metadata *md = &service->metadata[i];
370         int offset;
371
372         if (md->setting == Metadata_setting_postproc &&
373             (offset = settings_lookup_offset(service, md->name)) >= 0)
374         {
375             const char *val = session_setting_oneval(sdb, offset);
376             if (val)
377             {
378                 xmlNode *n = xmlNewTextChild(root, 0, (xmlChar *) "metadata",
379                                              (xmlChar *) val);
380                 xmlSetProp(n, (xmlChar *) "type", (xmlChar *) md->name);
381             }
382         }
383     }
384 }
385
386 static xmlDoc *normalize_record(struct session *se,
387                                 struct session_database *sdb,
388                                 struct conf_service *service,
389                                 const char *rec, NMEM nmem)
390 {
391     xmlDoc *rdoc = record_to_xml(se, sdb, rec);
392
393     if (rdoc)
394     {
395         char *parms[MAX_XSLT_ARGS*2+1];
396
397         insert_settings_parameters(sdb, service, parms, nmem);
398
399         if (normalize_record_transform(sdb->map, &rdoc, (const char **)parms))
400         {
401             session_log(se, YLOG_WARN, "Normalize failed");
402         }
403     }
404     return rdoc;
405 }
406
407 void session_settings_dump(struct session *se,
408                            struct session_database *db,
409                            WRBUF w)
410 {
411     if (db->settings)
412     {
413         int i, num = db->num_settings;
414         for (i = 0; i < num; i++)
415         {
416             struct setting *s = db->settings[i];
417             for (;s ; s = s->next)
418             {
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, "\"/>");
424             }
425             if (db->settings[i])
426                 wrbuf_puts(w, "\n");
427         }
428     }
429 }
430
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)
434 {
435     if (offset >= db->num_settings || !db->settings[offset])
436         return "";
437     return db->settings[offset]->value;
438 }
439
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)
446 {
447     if (sdb->settings && !sdb->map)
448     {
449         const char *s;
450
451         if (sdb->settings[PZ_XSLT] &&
452             (s = session_setting_oneval(sdb, PZ_XSLT)))
453         {
454             char auto_stylesheet[256];
455
456             if (!strcmp(s, "auto"))
457             {
458                 const char *request_syntax = session_setting_oneval(
459                     sdb, PZ_REQUESTSYNTAX);
460                 if (request_syntax)
461                 {
462                     char *cp;
463                     yaz_snprintf(auto_stylesheet, sizeof(auto_stylesheet),
464                                  "%s.xsl", request_syntax);
465                     for (cp = auto_stylesheet; *cp; cp++)
466                     {
467                         /* deliberately only consider ASCII */
468                         if (*cp > 32 && *cp < 127)
469                             *cp = tolower(*cp);
470                     }
471                     s = auto_stylesheet;
472                 }
473                 else
474                 {
475                     session_log(se, YLOG_WARN,
476                                 "No pz:requestsyntax for auto stylesheet");
477                 }
478             }
479             sdb->map = normalize_cache_get(se->normalize_cache,
480                                            se->service, s);
481             if (!sdb->map)
482                 return -1;
483         }
484     }
485     return 0;
486 }
487
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,
490                                  void *data2)
491 {
492     struct session_watchentry *ent = data;
493
494     ent->fun = 0;
495     ent->data = 0;
496     ent->obs = 0;
497 }
498
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)
503 {
504     int ret;
505     session_enter(s, "session_set_watch");
506     if (s->watchlist[what].fun)
507         ret = -1;
508     else
509     {
510
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);
515         ret = 0;
516     }
517     session_leave(s, "session_set_watch");
518     return ret;
519 }
520
521 void session_alert_watch(struct session *s, int what)
522 {
523     assert(s);
524     session_enter(s, "session_alert_watch");
525     if (s->watchlist[what].fun)
526     {
527         /* our watch is no longer associated with http_channel */
528         void *data;
529         session_watchfun fun;
530
531         http_remove_observer(s->watchlist[what].obs);
532         fun  = s->watchlist[what].fun;
533         data = s->watchlist[what].data;
534
535         /* reset watch before fun is invoked - in case fun wants to set
536            it again */
537         s->watchlist[what].fun = 0;
538         s->watchlist[what].data = 0;
539         s->watchlist[what].obs = 0;
540
541         session_leave(s, "session_alert_watch");
542         session_log(s, YLOG_DEBUG,
543                     "Alert Watch: %d calling function: %p", what, fun);
544         fun(data);
545     }
546     else
547         session_leave(s,"session_alert_watch");
548 }
549
550 //callback for grep_databases
551 static void select_targets_callback(struct session *se,
552                                     struct session_database *db)
553 {
554     struct client *cl;
555     struct client_list *l;
556
557     for (l = se->clients_cached; l; l = l->next)
558         if (client_get_database(l->client) == db)
559             break;
560
561     if (l)
562         cl = l->client;
563     else
564     {
565         cl = client_create(db->database->id);
566         client_set_database(cl, db);
567
568         l = xmalloc(sizeof(*l));
569         l->client = cl;
570         l->next = se->clients_cached;
571         se->clients_cached = l;
572     }
573     client_set_session(cl, se);
574
575     l = xmalloc(sizeof(*l));
576     l->client = cl;
577     l->next = se->clients_active;
578     se->clients_active = l;
579 }
580
581 static void session_reset_active_clients(struct session *se,
582                                          struct client_list *new_list)
583 {
584     struct client_list *l;
585
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");
590
591     while (l)
592     {
593         struct client_list *l_next = l->next;
594
595         client_lock(l->client);
596         client_set_session(l->client, 0); /* mark client inactive */
597         client_unlock(l->client);
598
599         xfree(l);
600         l = l_next;
601     }
602 }
603
604 static void session_remove_cached_clients(struct session *se)
605 {
606     struct client_list *l;
607
608     session_reset_active_clients(se, 0);
609
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");
614
615     while (l)
616     {
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);
624         xfree(l);
625         l = l_next;
626     }
627 }
628
629 // Associates a set of clients with a session;
630 // Note: Session-databases represent databases with per-session
631 // setting overrides
632 static int select_targets(struct session *se, const char *filter)
633 {
634     return session_grep_databases(se, filter, select_targets_callback);
635 }
636
637 int session_active_clients(struct session *s)
638 {
639     struct client_list *l;
640     int res = 0;
641
642     for (l = s->clients_active; l; l = l->next)
643         if (client_is_active(l->client))
644             res++;
645
646     return res;
647 }
648
649 int session_is_preferred_clients_ready(struct session *s)
650 {
651     struct client_list *l;
652     int res = 0;
653
654     for (l = s->clients_active; l; l = l->next)
655         if (client_is_active_preferred(l->client))
656             res++;
657     session_log(s, YLOG_DEBUG, "Has %d active preferred clients.", res);
658     return res == 0;
659 }
660
661 static void session_clear_set(struct session *se, struct reclist_sortparms *sp)
662 {
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;
669     se->termlists = 0;
670     relevance_clear(se->relevance);
671
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;
678
679     session_log(se, YLOG_DEBUG, "clear_set session_sort: field=%s increasing=%d type=%d configured",
680             sp->name, sp->increasing, sp->type);
681
682     se->reclist = reclist_create(se->nmem);
683 }
684
685 void session_sort(struct session *se, struct reclist_sortparms *sp,
686                   const char *mergekey, const char *rank)
687 {
688     struct client_list *l;
689     const char *field = sp->name;
690     int increasing = sp->increasing;
691     int type  = sp->type;
692     int clients_research = 0;
693
694     session_enter(se, "session_sort");
695     session_log(se, YLOG_DEBUG, "session_sort field=%s increasing=%d type=%d",
696                 field, increasing, type);
697
698     if (rank && (!se->rank || strcmp(se->rank, rank)))
699     {
700         /* new rank must research/reingest anyway */
701         assert(rank);
702         xfree(se->rank);
703         se->rank = *rank ? xstrdup(rank) : 0;
704         clients_research = 1;
705         session_log(se, YLOG_DEBUG, "session_sort: new rank = %s",
706                     rank);
707     }
708     if (mergekey && (!se->mergekey || strcmp(se->mergekey, mergekey)))
709     {
710         /* new mergekey must research/reingest anyway */
711         assert(mergekey);
712         xfree(se->mergekey);
713         se->mergekey = *mergekey ? xstrdup(mergekey) : 0;
714         clients_research = 1;
715         session_log(se, YLOG_DEBUG, "session_sort: new mergekey = %s",
716                     mergekey);
717     }
718     if (clients_research == 0)
719     {
720         struct reclist_sortparms *sr;
721         for (sr = se->sorted_results; sr; sr = sr->next)
722             if (!reclist_sortparms_cmp(sr, sp))
723                 break;
724         if (sr)
725         {
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");
729             return;
730         }
731     }
732     session_log(se, YLOG_DEBUG, "session_sort: field=%s increasing=%d type=%d must fetch",
733                 field, increasing, type);
734
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)
740     {
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);
745     }
746     if (!clients_research || se->clients_starting)
747     {
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;
752         sr->type = type;
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");
757     }
758     else
759     {
760         se->clients_starting = 1;
761         session_log(se, YLOG_DEBUG,
762                     "session_sort: reset results due to %d clients researching",
763                     clients_research);
764         session_clear_set(se, sp);
765         session_log(se, YLOG_DEBUG, "Re- search/ingesting for clients due to change in sort order");
766
767         session_leave(se, "session_sort");
768         for (l = se->clients_active; l; l = l->next)
769         {
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);
775             }
776             else
777             {
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));
782             }
783         }
784         session_enter(se, "session_sort");
785         se->clients_starting = 0;
786         se->force_position = 0;
787         session_leave(se, "session_sort");
788     }
789 }
790
791 void session_stop(struct session *se)
792 {
793     struct client_list *l;
794     session_enter(se, "session_stop1");
795     if (se->clients_starting)
796     {
797         session_leave(se, "session_stop1");
798         return;
799     }
800     se->clients_starting = 1;
801     session_leave(se, "session_stop1");
802
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);
807
808     for (l = se->clients_active; l; l = l->next)
809     {
810         struct client *cl = l->client;
811         client_stop(cl);
812     }
813     session_enter(se, "session_stop2");
814     se->clients_starting = 0;
815     session_leave(se, "session_stop2");
816 }
817
818 enum pazpar2_error_code session_search(struct session *se,
819                                        const char *query,
820                                        const char *startrecs,
821                                        const char *maxrecs,
822                                        const char *filter,
823                                        const char *limit,
824                                        const char **addinfo,
825                                        const char **addinfo2,
826                                        struct reclist_sortparms *sp,
827                                        const char *mergekey,
828                                        const char *rank)
829 {
830     int live_channels = 0;
831     int no_working = 0;
832     int no_failed_query = 0;
833     int no_failed_limit = 0;
834     int no_sortmap = 0;
835     struct client_list *l;
836
837     session_log(se, YLOG_DEBUG, "Search");
838
839     *addinfo = 0;
840
841     session_enter(se, "session_search0");
842     if (se->clients_starting)
843     {
844         session_leave(se, "session_search0");
845         return PAZPAR2_NO_ERROR;
846     }
847     se->clients_starting = 1;
848     se->force_position = 0;
849     session_leave(se, "session_search0");
850
851     if (se->settings_modified) {
852         session_remove_cached_clients(se);
853     }
854     else
855         session_reset_active_clients(se, 0);
856
857     session_enter(se, "session_search");
858     se->settings_modified = 0;
859
860     if (mergekey)
861     {
862         xfree(se->mergekey);
863         se->mergekey = *mergekey ? xstrdup(mergekey) : 0;
864     }
865     if (rank)
866     {
867         xfree(se->rank);
868         se->rank = *rank ? xstrdup(rank) : 0;
869     }
870
871     session_clear_set(se, sp);
872     relevance_destroy(&se->relevance);
873
874     live_channels = select_targets(se, filter);
875     if (!live_channels)
876     {
877         session_leave(se, "session_search");
878         se->clients_starting = 0;
879         return PAZPAR2_NO_TARGETS;
880     }
881
882     facet_limits_destroy(se->facet_limits);
883     se->facet_limits = facet_limits_create(limit);
884     if (!se->facet_limits)
885     {
886         *addinfo = "limit";
887         session_leave(se, "session_search");
888         se->clients_starting = 0;
889         session_reset_active_clients(se, 0);
890         return PAZPAR2_MALFORMED_PARAMETER_VALUE;
891     }
892
893     session_leave(se, "session_search");
894
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);
899
900     for (l = se->clients_active; l; l = l->next)
901     {
902         int parse_ret;
903         struct client *cl = l->client;
904         client_parse_init(cl, 1);
905         if (prepare_map(se, client_get_database(cl)) < 0)
906             continue;
907
908         parse_ret = client_parse_query(cl, query, se->facet_limits, addinfo2);
909         if (parse_ret == -1)
910             no_failed_query++;
911         else if (parse_ret == -2)
912             no_failed_limit++;
913         else if (parse_ret < 0)
914             no_working++; /* other error, such as bad CCL map */
915         else
916         {
917             client_parse_range(cl, startrecs, maxrecs);
918             client_parse_sort(cl, sp, &no_sortmap);
919             client_start_search(cl);
920             no_working++;
921         }
922     }
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)
927     {
928         se->force_position = 1;
929         yaz_log(YLOG_LOG, "force_position=1");
930     }
931     se->clients_starting = 0;
932     session_leave(se, "session_search2");
933     if (no_working == 0)
934     {
935         if (no_failed_query > 0)
936         {
937             *addinfo = "query";
938             return PAZPAR2_MALFORMED_PARAMETER_VALUE;
939         }
940         else if (no_failed_limit > 0)
941         {
942             *addinfo = "limit";
943             return PAZPAR2_MALFORMED_PARAMETER_VALUE;
944         }
945         else
946             return PAZPAR2_NO_TARGETS;
947     }
948     return PAZPAR2_NO_ERROR;
949 }
950
951 // Creates a new session_database object for a database
952 static void session_init_databases_fun(void *context, struct database *db)
953 {
954     struct session *se = (struct session *) context;
955     struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
956     int i;
957
958     new->database = db;
959
960     new->map = 0;
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++)
966     {
967         struct setting *setting = db->settings[i];
968         new->settings[i] = setting;
969     }
970     new->next = se->databases;
971     se->databases = new;
972 }
973
974 // Doesn't free memory associated with sdb -- nmem takes care of that
975 static void session_database_destroy(struct session_database *sdb)
976 {
977     sdb->map = 0;
978 }
979
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)
983 {
984     se->databases = 0;
985     predef_grep_databases(se, se->service, session_init_databases_fun);
986 }
987
988 // Probably session_init_databases_fun should be refactored instead of
989 // called here.
990 static struct session_database *load_session_database(struct session *se,
991                                                       const char *id)
992 {
993     struct database *db = new_database_inherit_settings(id, se->session_nmem, se->service->settings);
994     session_init_databases_fun((void*) se, db);
995
996     // New sdb is head of se->databases list
997     return se->databases;
998 }
999
1000 // Find an existing session database. If not found, load it
1001 static struct session_database *find_session_database(struct session *se,
1002                                                       const char *id)
1003 {
1004     struct session_database *sdb;
1005
1006     for (sdb = se->databases; sdb; sdb = sdb->next)
1007         if (!strcmp(sdb->database->id, id))
1008             return sdb;
1009     return load_session_database(se, id);
1010 }
1011
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)
1015 {
1016     session_enter(se, "session_apply_setting");
1017     {
1018         struct session_database *sdb = find_session_database(se, dbname);
1019         struct conf_service *service = se->service;
1020         struct setting *s;
1021         int offset = settings_create_offset(service, name);
1022
1023         expand_settings_array(&sdb->settings, &sdb->num_settings, offset,
1024                               se->session_nmem);
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)
1028             sdb->map = 0;
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))
1033                 break;
1034         if (!s)
1035         {
1036             s = nmem_malloc(se->session_nmem, sizeof(*s));
1037             s->precedence = 0;
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;
1042         }
1043         s->value = nmem_strdup(se->session_nmem, value);
1044     }
1045     session_leave(se, "session_apply_setting");
1046 }
1047
1048 void session_destroy(struct session *se)
1049 {
1050     struct session_database *sdb;
1051     int i = session_use(-1);
1052
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);
1057
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);
1064     xfree(se->rank);
1065     facet_limits_destroy(se->facet_limits);
1066     nmem_destroy(se->nmem);
1067     service_destroy(se->service);
1068     yaz_mutex_destroy(&se->session_mutex);
1069 }
1070
1071 size_t session_get_memory_status(struct session *session) {
1072     size_t session_nmem;
1073     if (session == 0)
1074         return 0;
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;
1079 }
1080
1081
1082 struct session *new_session(NMEM nmem, struct conf_service *service,
1083                             unsigned session_id)
1084 {
1085     int i;
1086     struct session *session = nmem_malloc(nmem, sizeof(*session));
1087
1088     char tmp_str[50];
1089
1090     sprintf(tmp_str, "session#%u", session_id);
1091
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;
1111     session->rank = 0;
1112     session->clients_starting = 0;
1113     session->force_position = 0;
1114
1115     for (i = 0; i <= SESSION_WATCH_MAX; i++)
1116     {
1117         session->watchlist[i].data = 0;
1118         session->watchlist[i].fun = 0;
1119     }
1120     session->normalize_cache = normalize_cache_create();
1121     session->session_mutex = 0;
1122     pazpar2_mutex_create(&session->session_mutex, tmp_str);
1123
1124     i = session_use(1);
1125     session_log(session, YLOG_LOG, "create session-total %d", i);
1126     return session;
1127 }
1128
1129 static struct hitsbytarget *hitsbytarget_nb(struct session *se,
1130                                             int *count, NMEM nmem)
1131 {
1132     struct hitsbytarget *res = 0;
1133     struct client_list *l;
1134     size_t sz = 0;
1135
1136     for (l = se->clients_active; l; l = l->next)
1137         sz++;
1138
1139     res = nmem_malloc(nmem, sizeof(*res) * sz);
1140     *count = 0;
1141     for (l = se->clients_active; l; l = l->next)
1142     {
1143         struct client *cl = l->client;
1144         WRBUF w = wrbuf_alloc();
1145         const char *name = session_setting_oneval(client_get_database(cl),
1146                                                   PZ_NAME);
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,
1153                                                      0, 0);
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));
1161         wrbuf_rewind(w);
1162         res[*count].suggestions_xml =
1163             nmem_strdup(nmem, client_get_suggestions_xml(cl, w));
1164
1165         res[*count].query_data =
1166             client_get_query(cl, &res[*count].query_type, nmem);
1167         wrbuf_destroy(w);
1168         (*count)++;
1169     }
1170     return res;
1171 }
1172
1173 struct hitsbytarget *get_hitsbytarget(struct session *se, int *count, NMEM nmem)
1174 {
1175     struct hitsbytarget *p;
1176     session_enter(se, "get_hitsbytarget");
1177     p = hitsbytarget_nb(se, count, nmem);
1178     session_leave(se, "get_hitsbytarget");
1179     return p;
1180 }
1181
1182 // Compares two hitsbytarget nodes by hitcount
1183 static int cmp_ht(const void *p1, const void *p2)
1184 {
1185     const struct hitsbytarget *h1 = p1;
1186     const struct hitsbytarget *h2 = p2;
1187     return h2->hits - h1->hits;
1188 }
1189
1190 // Compares two hitsbytarget nodes by hitcount
1191 static int cmp_ht_approx(const void *p1, const void *p2)
1192 {
1193     const struct hitsbytarget *h1 = p1;
1194     const struct hitsbytarget *h2 = p2;
1195     return h2->approximation - h1->approximation;
1196 }
1197
1198 static int targets_termlist_nb(WRBUF wrbuf, struct session *se, int num,
1199                                NMEM nmem, int version)
1200 {
1201     struct hitsbytarget *ht;
1202     int count, i;
1203
1204     ht = hitsbytarget_nb(se, &count, nmem);
1205     if (version >= 2)
1206         qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht_approx);
1207     else
1208         qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht);
1209     for (i = 0; i < count && i < num && ht[i].hits > 0; i++)
1210     {
1211
1212         // do only print terms which have display names
1213
1214         wrbuf_puts(wrbuf, "<term>\n");
1215
1216         wrbuf_puts(wrbuf, "<id>");
1217         wrbuf_xmlputs(wrbuf, ht[i].id);
1218         wrbuf_puts(wrbuf, "</id>\n");
1219
1220         wrbuf_puts(wrbuf, "<name>");
1221         if (!ht[i].name || !ht[i].name[0])
1222             wrbuf_xmlputs(wrbuf, "NO TARGET NAME");
1223         else
1224             wrbuf_xmlputs(wrbuf, ht[i].name);
1225         wrbuf_puts(wrbuf, "</name>\n");
1226
1227         wrbuf_printf(wrbuf, "<frequency>" ODR_INT_PRINTF "</frequency>\n",
1228                      ht[i].hits);
1229
1230         if (version >= 2) {
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);
1235         }
1236
1237         wrbuf_puts(wrbuf, "<state>");
1238         wrbuf_xmlputs(wrbuf, ht[i].state);
1239         wrbuf_puts(wrbuf, "</state>\n");
1240
1241         wrbuf_printf(wrbuf, "<diagnostic>%d</diagnostic>\n",
1242                      ht[i].diagnostic);
1243         wrbuf_puts(wrbuf, "</term>\n");
1244     }
1245     return count;
1246 }
1247
1248 void perform_termlist(struct http_channel *c, struct session *se,
1249                       const char *name, int num, int version)
1250 {
1251     int j;
1252     NMEM nmem_tmp = nmem_create();
1253     char **names;
1254     int num_names = 0;
1255
1256     if (!name)
1257         name = "*";
1258
1259     nmem_strsplit(nmem_tmp, ",", name, &names, &num_names);
1260
1261     session_enter(se, "perform_termlist");
1262
1263     for (j = 0; j < num_names; j++)
1264     {
1265         const char *tname;
1266         int must_generate_empty = 1; /* bug 5350 */
1267
1268         struct named_termlist *t = se->termlists;
1269         for (; t; t = t->next)
1270         {
1271             tname = t->name;
1272             if (!strcmp(names[j], tname) || !strcmp(names[j], "*"))
1273             {
1274                 struct termlist_score **p = 0;
1275                 int len;
1276
1277                 wrbuf_puts(c->wrbuf, "<list name=\"");
1278                 wrbuf_xmlputs(c->wrbuf, tname);
1279                 wrbuf_puts(c->wrbuf, "\">\n");
1280                 must_generate_empty = 0;
1281
1282                 p = termlist_highscore(t->termlist, &len, nmem_tmp);
1283                 if (p)
1284                 {
1285                     int i;
1286                     for (i = 0; i < len && i < num; i++)
1287                     {
1288                         // prevent sending empty term elements
1289                         if (!p[i]->display_term || !p[i]->display_term[0])
1290                             continue;
1291
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>",
1298                                      p[i]->frequency);
1299                         wrbuf_puts(c->wrbuf, "</term>\n");
1300                     }
1301                 }
1302                 wrbuf_puts(c->wrbuf, "</list>\n");
1303             }
1304         }
1305         tname = "xtargets";
1306         if (!strcmp(names[j], tname) || !strcmp(names[j], "*"))
1307         {
1308             wrbuf_puts(c->wrbuf, "<list name=\"");
1309             wrbuf_xmlputs(c->wrbuf, tname);
1310             wrbuf_puts(c->wrbuf, "\">\n");
1311
1312             targets_termlist_nb(c->wrbuf, se, num, c->nmem, version);
1313             wrbuf_puts(c->wrbuf, "</list>\n");
1314             must_generate_empty = 0;
1315         }
1316         if (must_generate_empty)
1317         {
1318             wrbuf_puts(c->wrbuf, "<list name=\"");
1319             wrbuf_xmlputs(c->wrbuf, names[j]);
1320             wrbuf_puts(c->wrbuf, "\"/>\n");
1321         }
1322     }
1323     session_leave(se, "perform_termlist");
1324     nmem_destroy(nmem_tmp);
1325 }
1326
1327 #ifdef MISSING_HEADERS
1328 void report_nmem_stats(void)
1329 {
1330     size_t in_use, is_free;
1331
1332     nmem_get_memory_in_use(&in_use);
1333     nmem_get_memory_free(&is_free);
1334
1335     yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1336             (long) in_use, (long) is_free);
1337 }
1338 #endif
1339
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)
1343 {
1344     struct record_cluster *r = 0;
1345
1346     session_enter(se, "show_single_start");
1347     *prev_r = 0;
1348     *next_r = 0;
1349     reclist_limit(se->reclist, se, 1);
1350
1351     reclist_enter(se->reclist);
1352     while ((r = reclist_read_record(se->reclist)))
1353     {
1354         if (!strcmp(r->recid, id))
1355         {
1356             *next_r = reclist_read_record(se->reclist);
1357             break;
1358         }
1359         *prev_r = r;
1360     }
1361     reclist_leave(se->reclist);
1362     if (!r)
1363         session_leave(se, "show_single_start");
1364     return r;
1365 }
1366
1367 void show_single_stop(struct session *se, struct record_cluster *rec)
1368 {
1369     session_leave(se, "show_single_stop");
1370 }
1371
1372
1373 int session_fetch_more(struct session *se)
1374 {
1375     struct client_list *l;
1376     int ret = 0;
1377
1378     for (l = se->clients_active; l; l = l->next)
1379     {
1380         struct client *cl = l->client;
1381         if (client_get_state(cl) == Client_Idle)
1382         {
1383             if (client_fetch_more(cl))
1384             {
1385                 session_log(se, YLOG_LOG, "%s: more to fetch",
1386                             client_get_id(cl));
1387                 ret = 1;
1388             }
1389             else
1390             {
1391                 int filtered;
1392                 int ingest_failures;
1393                 int record_failures;
1394                 int num = client_get_num_records(
1395                     cl, &filtered, &ingest_failures, &record_failures);
1396
1397                 session_log(se, YLOG_LOG, "%s: hits=" ODR_INT_PRINTF
1398                             " fetched=%d filtered=%d",
1399                             client_get_id(cl),
1400                             client_get_hits(cl),
1401                             num, filtered);
1402                 if (ingest_failures || record_failures)
1403                 {
1404                     session_log(se, YLOG_WARN, "%s:"
1405                                 " ingest failures=%d record failures=%d",
1406                                 client_get_id(cl),
1407                                 ingest_failures, record_failures);
1408                 }
1409             }
1410         }
1411         else
1412         {
1413             session_log(se, YLOG_LOG, "%s: no fetch due to state=%s",
1414                         client_get_id(cl), client_get_state_str(cl));
1415         }
1416
1417     }
1418     return ret;
1419 }
1420
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)
1427 {
1428     struct record_cluster **recs = 0;
1429     struct reclist_sortparms *spp;
1430     struct client_list *l;
1431     int i;
1432     NMEM nmem_tmp = 0;
1433 #if USE_TIMING
1434     yaz_timing_t t = yaz_timing_create();
1435 #endif
1436     session_enter(se, "show_range_start");
1437     *sumhits = 0;
1438     *approx_hits = 0;
1439     *total = 0;
1440     reclist_limit(se->reclist, se, 0);
1441     if (se->relevance)
1442     {
1443         for (spp = sp; spp; spp = spp->next)
1444             if (spp->type == Metadata_type_relevance)
1445             {
1446                 relevance_prepare_read(se->relevance, se->reclist);
1447                 break;
1448             }
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);
1452         }
1453     }
1454     if (se->force_position)
1455     {
1456         nmem_tmp = nmem_create();
1457         sp = reclist_parse_sortparms(nmem_tmp, "position:1", 0);
1458         assert(sp);
1459     }
1460     reclist_sort(se->reclist, sp);
1461     if (nmem_tmp)
1462         nmem_destroy(nmem_tmp);
1463
1464     reclist_enter(se->reclist);
1465     *total = reclist_get_num_records(se->reclist);
1466
1467     for (l = se->clients_active; l; l = l->next)
1468         client_update_show_stat(l->client, 0);
1469
1470     for (i = 0; i < start; i++)
1471     {
1472         struct record_cluster *r = reclist_read_record(se->reclist);
1473         if (!r)
1474         {
1475             *num = 0;
1476             break;
1477         }
1478         else
1479         {
1480             struct record *rec = r->records;
1481             for (;rec; rec = rec->next)
1482                 client_update_show_stat(rec->client, 1);
1483         }
1484     }
1485     recs = nmem_malloc(se->nmem, (*num > 0 ? *num : 1) * sizeof(*recs));
1486     for (i = 0; i < *num; i++)
1487     {
1488         struct record_cluster *r = reclist_read_record(se->reclist);
1489         if (!r)
1490         {
1491             *num = i;
1492             break;
1493         }
1494         else
1495         {
1496             struct record *rec = r->records;
1497             for (;rec; rec = rec->next)
1498                 client_update_show_stat(rec->client, 1);
1499             recs[i] = r;
1500         }
1501     }
1502     reclist_leave(se->reclist);
1503 #if USE_TIMING
1504     yaz_timing_stop(t);
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);
1509 #endif
1510
1511     if (!session_fetch_more(se))
1512         session_log(se, YLOG_LOG, "can not fetch more");
1513     else
1514     {
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))
1519         {
1520             session_log(se, YLOG_WARN, "Ignoring show block");
1521             session_enter(se, "show_range_start");
1522         }
1523         else
1524         {
1525             session_log(se, YLOG_LOG, "session watch OK");
1526             return 0;
1527         }
1528     }
1529     return recs;
1530 }
1531
1532 void show_range_stop(struct session *se, struct record_cluster **recs)
1533 {
1534     session_leave(se, "show_range_stop");
1535 }
1536
1537 void statistics(struct session *se, struct statistics *stat)
1538 {
1539     struct client_list *l;
1540     int count = 0;
1541
1542     memset(stat, 0, sizeof(*stat));
1543     stat->num_hits = 0;
1544     for (l = se->clients_active; l; l = l->next)
1545     {
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))
1551         {
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;
1557         default: break;
1558         }
1559         count++;
1560     }
1561     stat->num_records = se->total_records;
1562
1563     stat->num_clients = count;
1564 }
1565
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)
1570 {
1571     struct record_metadata *rec_md = record_metadata_create(nmem);
1572     struct record_metadata_attr **attrp = &rec_md->attributes;
1573
1574     for (; attr; attr = attr->next)
1575     {
1576         if (attr->children && attr->children->content)
1577         {
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));
1584                 (*attrp)->name =
1585                     nmem_strdup(nmem, (const char *) attr->name);
1586                 (*attrp)->value =
1587                     nmem_strdup(nmem, (const char *) attr->children->content);
1588                 attrp = &(*attrp)->next;
1589             }
1590         }
1591     }
1592     *attrp = 0;
1593
1594     switch (type)
1595     {
1596     case Metadata_type_generic:
1597     case Metadata_type_skiparticle:
1598         if (norm)
1599         {
1600             rec_md->data.text.disp = nmem_strdup(nmem, value);
1601             rec_md->data.text.norm = nmem_strdup(nmem, norm);
1602         }
1603         else
1604         {
1605             if (strstr(value, "://")) /* looks like a URL */
1606                 rec_md->data.text.disp = nmem_strdup(nmem, value);
1607             else
1608                 rec_md->data.text.disp =
1609                     normalize7bit_generic(nmem_strdup(nmem, value), " ,/.:([");
1610             rec_md->data.text.norm = rec_md->data.text.disp;
1611         }
1612         rec_md->data.text.sort = 0;
1613         rec_md->data.text.snippet = 0;
1614         break;
1615     case Metadata_type_year:
1616     case Metadata_type_date:
1617     {
1618         int first, last;
1619         int longdate = 0;
1620
1621         if (type == Metadata_type_date)
1622             longdate = 1;
1623         if (extract7bit_dates((char *) value, &first, &last, longdate) < 0)
1624             return 0;
1625
1626         rec_md->data.number.min = first;
1627         rec_md->data.number.max = last;
1628     }
1629     break;
1630     case Metadata_type_float:
1631         rec_md->data.fnumber = atof(value);
1632         break;
1633     case Metadata_type_relevance:
1634     case Metadata_type_position:
1635     case Metadata_type_retrieval:
1636         return 0;
1637     }
1638     return rec_md;
1639 }
1640
1641 static void mergekey_norm_wr(pp2_charset_fact_t charsets,
1642                              WRBUF norm_wr, const char *value)
1643 {
1644     const char *norm_str;
1645     pp2_charset_token_t prt =
1646         pp2_charset_token_create(charsets, "mergekey");
1647
1648     pp2_charset_token_first(prt, value, 0);
1649     while ((norm_str = pp2_charset_token_next(prt)))
1650     {
1651         if (*norm_str)
1652         {
1653             if (wrbuf_len(norm_wr))
1654                 wrbuf_puts(norm_wr, " ");
1655             wrbuf_puts(norm_wr, norm_str);
1656         }
1657     }
1658     pp2_charset_token_destroy(prt);
1659 }
1660
1661 static int get_mergekey_from_doc(xmlDoc *doc, xmlNode *root, const char *name,
1662                                  struct conf_service *service, WRBUF norm_wr)
1663 {
1664     xmlNode *n;
1665     int no_found = 0;
1666     for (n = root->children; n; n = n->next)
1667     {
1668         if (n->type != XML_ELEMENT_NODE)
1669             continue;
1670         if (!strcmp((const char *) n->name, "metadata"))
1671         {
1672             const char *type = yaz_xml_get_prop(n, "type");
1673             if (type == NULL) {
1674                 yaz_log(YLOG_FATAL, "Missing type attribute on metadata element. Skipping!");
1675             }
1676             else if (!strcmp(name, (const char *) type))
1677             {
1678                 xmlChar *value = xmlNodeListGetString(doc, n->children, 1);
1679                 if (value && *value)
1680                 {
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);
1686                     no_found++;
1687                 }
1688                 if (value)
1689                     xmlFree(value);
1690             }
1691         }
1692     }
1693     return no_found;
1694 }
1695
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)
1700 {
1701     char *mergekey_norm = 0;
1702     WRBUF norm_wr = wrbuf_alloc();
1703     const char *mergekey;
1704
1705     if (session_mergekey)
1706     {
1707         int i, num = 0;
1708         char **values = 0;
1709         nmem_strsplit_escape2(nmem, ",", session_mergekey, &values,
1710                               &num, 1, '\\', 1);
1711
1712         for (i = 0; i < num; i++)
1713             get_mergekey_from_doc(doc, root, values[i], service, norm_wr);
1714     }
1715     else if ((mergekey = yaz_xml_get_prop(root, "mergekey")))
1716     {
1717         mergekey_norm_wr(service->charsets, norm_wr, mergekey);
1718     }
1719     else
1720     {
1721         /* no mergekey defined in XSL. Look for mergekey metadata instead */
1722         int field_id;
1723         for (field_id = 0; field_id < service->num_metadata; field_id++)
1724         {
1725             struct conf_metadata *ser_md = &service->metadata[field_id];
1726             if (ser_md->mergekey != Metadata_mergekey_no)
1727             {
1728                 int r = get_mergekey_from_doc(doc, root, ser_md->name,
1729                                               service, norm_wr);
1730                 if (r == 0 && ser_md->mergekey == Metadata_mergekey_required)
1731                 {
1732                     /* no mergekey on this one and it is required..
1733                        Generate unique key instead */
1734                     wrbuf_rewind(norm_wr);
1735                     break;
1736                 }
1737             }
1738         }
1739     }
1740
1741     /* generate unique key if none is not generated already or is empty */
1742     if (wrbuf_len(norm_wr) == 0)
1743     {
1744         wrbuf_printf(norm_wr, "position: %s-%06d",
1745                      client_get_id(cl), record_no);
1746     }
1747     else
1748     {
1749         const char *lead = "content: ";
1750         wrbuf_insert(norm_wr, 0, lead, strlen(lead));
1751     }
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;
1756 }
1757
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
1763
1764     If there is no pz:recordfilter defined, this function returns 1
1765     as well.
1766 */
1767
1768 static int check_record_filter(xmlNode *root, struct session_database *sdb)
1769 {
1770     int match = 0;
1771     xmlNode *n;
1772     const char *s;
1773     s = session_setting_oneval(sdb, PZ_RECORDFILTER);
1774
1775     if (!s || !*s)
1776         return 1;
1777
1778     for (n = root->children; n; n = n->next)
1779     {
1780         if (n->type != XML_ELEMENT_NODE)
1781             continue;
1782         if (!strcmp((const char *) n->name, "metadata"))
1783         {
1784             const char *type = yaz_xml_get_prop(n, "type");
1785             if (type)
1786             {
1787                 size_t len;
1788                 int substring;
1789                 const char *eq;
1790
1791                 if ((eq = strchr(s, '=')))
1792                     substring = 0;
1793                 else if ((eq = strchr(s, '~')))
1794                     substring = 1;
1795                 if (eq)
1796                     len = eq - s;
1797                 else
1798                     len = strlen(s);
1799                 if (len == strlen((const char *)type) &&
1800                     !memcmp((const char *) type, s, len))
1801                 {
1802                     xmlChar *value = xmlNodeGetContent(n);
1803                     if (value && *value)
1804                     {
1805                         if (!eq ||
1806                             (substring && strstr((const char *) value, eq+1)) ||
1807                             (!substring && !strcmp((const char *) value, eq + 1)))
1808                             match = 1;
1809                     }
1810                     xmlFree(value);
1811                 }
1812             }
1813         }
1814     }
1815     return match;
1816 }
1817
1818 static int ingest_to_cluster(struct client *cl,
1819                              WRBUF wrbuf_disp,
1820                              WRBUF wrbuf_norm,
1821                              xmlDoc *xdoc,
1822                              xmlNode *root,
1823                              int record_no,
1824                              struct record_metadata_attr *mergekey);
1825
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)
1830 {
1831     int ret = 0;
1832     struct session *se = client_get_session(cl);
1833     WRBUF wrbuf_disp, wrbuf_norm;
1834
1835     if (!check_record_filter(root, sdb))
1836     {
1837         session_log(se, YLOG_LOG,
1838                     "Filtered out record no %d from %s",
1839                     record_no, sdb->database->id);
1840         return 0;
1841     }
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);
1851     return ret;
1852 }
1853
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
1859     \retval 0 OK
1860     \retval -1 failure
1861     \retval -2 Filtered
1862 */
1863 int ingest_record(struct client *cl, const char *rec,
1864                   int record_no, NMEM nmem)
1865 {
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);
1872     return r;
1873 }
1874
1875 int ingest_xml_record(struct client *cl, xmlDoc *xdoc,
1876                       int record_no, NMEM nmem, int cached_copy)
1877 {
1878     struct session *se = client_get_session(cl);
1879     struct session_database *sdb = client_get_database(cl);
1880     struct conf_service *service = se->service;
1881     xmlNode *root;
1882     int r = 0;
1883     if (!xdoc)
1884         return -1;
1885
1886     if (global_parameters.dump_records)
1887     {
1888         session_log(se, YLOG_LOG, "Normalized record from %s",
1889                     sdb->database->id);
1890         log_xml_doc(xdoc);
1891     }
1892
1893     root = xmlDocGetRootElement(xdoc);
1894
1895     if (!strcmp((const char *) root->name, "cluster"))
1896     {
1897         int no_merge_keys = 0;
1898         int no_merge_dups = 0;
1899         xmlNode *sroot;
1900         struct record_metadata_attr *mk = 0;
1901
1902         for (sroot = root->children; sroot; sroot = sroot->next)
1903             if (sroot->type == XML_ELEMENT_NODE &&
1904                 !strcmp((const char *) sroot->name, "record"))
1905             {
1906                 struct record_metadata_attr **mkp;
1907                 const char *mergekey_norm =
1908                     get_mergekey(xdoc, sroot, cl, record_no, service, nmem,
1909                                  se->mergekey);
1910                 if (!mergekey_norm)
1911                 {
1912                     r = -1;
1913                     break;
1914                 }
1915                 for (mkp = &mk; *mkp; mkp = &(*mkp)->next)
1916                     if (!strcmp((*mkp)->value, mergekey_norm))
1917                         break;
1918                 if (!*mkp)
1919                 {
1920                     *mkp = (struct record_metadata_attr*)
1921                         nmem_malloc(nmem, sizeof(**mkp));
1922                     (*mkp)->name = 0;
1923                     (*mkp)->value = nmem_strdup(nmem, mergekey_norm);
1924                     (*mkp)->next = 0;
1925                     no_merge_keys++;
1926                 }
1927                 else
1928                     no_merge_dups++;
1929             }
1930         if (no_merge_keys > 1 || no_merge_dups > 0)
1931         {
1932             yaz_log(YLOG_LOG, "Got %d mergekeys, %d dups for position %d",
1933                     no_merge_keys, no_merge_dups, record_no);
1934         }
1935         for (sroot = root->children; !r && sroot; sroot = sroot->next)
1936             if (sroot->type == XML_ELEMENT_NODE &&
1937                 !strcmp((const char *) sroot->name, "record"))
1938             {
1939                 if (!cached_copy)
1940                     insert_settings_values(sdb, xdoc, root, service);
1941                 r = ingest_sub_record(cl, xdoc, sroot, record_no, nmem, sdb,
1942                                       mk);
1943             }
1944     }
1945     else if (!strcmp((const char *) root->name, "record"))
1946     {
1947         const char *mergekey_norm =
1948             get_mergekey(xdoc, root, cl, record_no, service, nmem,
1949                          se->mergekey);
1950         if (mergekey_norm)
1951         {
1952             struct record_metadata_attr *mk = (struct record_metadata_attr*)
1953                 nmem_malloc(nmem, sizeof(*mk));
1954             mk->name = 0;
1955             mk->value = nmem_strdup(nmem, mergekey_norm);
1956             mk->next = 0;
1957
1958             if (!cached_copy)
1959                 insert_settings_values(sdb, xdoc, root, service);
1960             r = ingest_sub_record(cl, xdoc, root, record_no, nmem, sdb, mk);
1961         }
1962     }
1963     else
1964     {
1965         session_log(se, YLOG_WARN, "Bad pz root element: %s",
1966                     (const char *) root->name);
1967         r = -1;
1968     }
1969     return r;
1970 }
1971
1972
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)
1979 {
1980     int i;
1981     struct record_metadata *rec_md = rec_md0;
1982     WRBUF val_wr = 0;
1983     WRBUF text_wr = wrbuf_alloc();
1984     for (i = 0; i < num_v; )
1985     {
1986         if (rec_md)
1987         {
1988             if (ser_md->type == Metadata_type_year
1989                 || ser_md->type == Metadata_type_date)
1990             {
1991                 int y = atoi(values[i]);
1992                 if (y >= rec_md->data.number.min
1993                     && y <= rec_md->data.number.max)
1994                     break;
1995             }
1996             else
1997             {
1998                 if (!val_wr)
1999                 {
2000                     val_wr = wrbuf_alloc();
2001                     mergekey_norm_wr(service->charsets, val_wr, values[i]);
2002                 }
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)))
2007                     break;
2008             }
2009             rec_md = rec_md->next;
2010         }
2011         else
2012         {
2013             rec_md = rec_md0;
2014             wrbuf_destroy(val_wr);
2015             val_wr = 0;
2016             i++;
2017         }
2018     }
2019     wrbuf_destroy(val_wr);
2020     wrbuf_destroy(text_wr);
2021     return i < num_v ? 1 : 0;
2022 }
2023
2024 int session_check_cluster_limit(struct session *se, struct record_cluster *rec)
2025 {
2026     int i;
2027     struct conf_service *service = se->service;
2028     int ret = 1;
2029     const char *name;
2030     const char *value;
2031     NMEM nmem_tmp = nmem_create();
2032
2033     for (i = 0; (name = facet_limits_get(se->facet_limits, i, &value)); i++)
2034     {
2035         int j;
2036         for (j = 0; j < service->num_metadata; j++)
2037         {
2038             struct conf_metadata *md = service->metadata + j;
2039             if (!strcmp(md->name, name) && md->limitcluster)
2040             {
2041                 char **values = 0;
2042                 int num = 0;
2043                 int md_field_id =
2044                     conf_service_metadata_field_id(service,
2045                                                    md->limitcluster);
2046
2047                 if (md_field_id < 0)
2048                 {
2049                     ret = 0;
2050                     break;
2051                 }
2052
2053                 nmem_strsplit_escape2(nmem_tmp, "|", value, &values,
2054                                       &num, 1, '\\', 1);
2055
2056                 if (!match_metadata_local(service,
2057                                           &service->metadata[md_field_id],
2058                                           rec->metadata[md_field_id],
2059                                           values, num))
2060                 {
2061                     ret = 0;
2062                     break;
2063                 }
2064             }
2065         }
2066     }
2067     nmem_destroy(nmem_tmp);
2068     return ret;
2069 }
2070
2071 // Skip record on non-zero
2072 static int check_limit_local(struct client *cl,
2073                              struct record *record,
2074                              int record_no)
2075 {
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);
2081     int l = 0;
2082     while (!skip_record)
2083     {
2084         int md_field_id;
2085         char **values = 0;
2086         int num_v = 0;
2087         const char *name =
2088             client_get_facet_limit_local(cl, sdb, &l, nmem_tmp,
2089                                          &num_v, &values);
2090         if (!name)
2091             break;
2092
2093         if (!strcmp(name, "*"))
2094         {
2095             for (md_field_id = 0; md_field_id < service->num_metadata;
2096                  md_field_id++)
2097             {
2098                 if (match_metadata_local(
2099                         service,
2100                         &service->metadata[md_field_id],
2101                         record->metadata[md_field_id],
2102                         values, num_v))
2103                     break;
2104             }
2105             if (md_field_id == service->num_metadata)
2106                 skip_record = 1;
2107         }
2108         else
2109         {
2110             md_field_id = conf_service_metadata_field_id(service, name);
2111             if (md_field_id < 0)
2112             {
2113                 skip_record = 1;
2114                 break;
2115             }
2116             if (!match_metadata_local(
2117                     service,
2118                     &service->metadata[md_field_id],
2119                     record->metadata[md_field_id],
2120                     values, num_v))
2121             {
2122                 skip_record = 1;
2123             }
2124         }
2125     }
2126     nmem_destroy(nmem_tmp);
2127     return skip_record;
2128 }
2129
2130 static int ingest_to_cluster(struct client *cl,
2131                              WRBUF wrbuf_disp,
2132                              WRBUF wrbuf_norm,
2133                              xmlDoc *xdoc,
2134                              xmlNode *root,
2135                              int record_no,
2136                              struct record_metadata_attr *merge_keys)
2137 {
2138     xmlNode *n;
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;
2147     int rank_num = 0;
2148     struct record *record = record_create(se->nmem,
2149                                           service->num_metadata,
2150                                           service->num_sortkeys, cl,
2151                                           record_no);
2152
2153     for (n = root->children; n; n = n->next)
2154     {
2155         if (n->type != XML_ELEMENT_NODE)
2156             continue;
2157         if (!strcmp((const char *) n->name, "metadata"))
2158         {
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;
2163             xmlChar *value0;
2164             const char *type = yaz_xml_get_prop(n, "type");
2165
2166             if (!type)
2167                 continue;
2168
2169             md_field_id
2170                 = conf_service_metadata_field_id(service, (const char *) type);
2171             if (md_field_id < 0)
2172             {
2173                 if (se->number_of_warnings_unknown_metadata == 0)
2174                 {
2175                     session_log(se, YLOG_WARN,
2176                             "Ignoring unknown metadata element: %s", type);
2177                 }
2178                 se->number_of_warnings_unknown_metadata++;
2179                 continue;
2180             }
2181
2182             wrbuf_rewind(wrbuf_disp);
2183             value0 = xmlNodeListGetString(xdoc, n->children, 1);
2184             if (!value0 || !*value0)
2185             {
2186                 const char *empty = yaz_xml_get_prop(n, "empty");
2187                 if (!empty)
2188                     continue;
2189                 wrbuf_puts(wrbuf_disp, (const char *) empty);
2190             }
2191             else
2192             {
2193                 wrbuf_puts(wrbuf_disp, (const char *) value0);
2194             }
2195             if (value0)
2196                 xmlFree(value0);
2197             ser_md = &service->metadata[md_field_id];
2198
2199             // non-merged metadata
2200             rec_md = record_metadata_init(se->nmem, wrbuf_cstr(wrbuf_disp), 0,
2201                                           ser_md->type, n->properties);
2202             if (!rec_md)
2203             {
2204                 session_log(se, YLOG_WARN, "bad metadata data '%s' "
2205                             "for element '%s'", wrbuf_cstr(wrbuf_disp), type);
2206                 continue;
2207             }
2208
2209             if (ser_md->type == Metadata_type_generic)
2210             {
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,
2215                                                             wrbuf_cstr(w));
2216                 wrbuf_destroy(w);
2217             }
2218
2219
2220             wheretoput = &record->metadata[md_field_id];
2221             while (*wheretoput)
2222                 wheretoput = &(*wheretoput)->next;
2223             *wheretoput = rec_md;
2224         }
2225     }
2226
2227     if (check_limit_local(cl, record, record_no))
2228     {
2229         return -2;
2230     }
2231     cluster = reclist_insert(se->reclist, se->relevance, service, record,
2232                              merge_keys, &se->total_merged);
2233     if (!cluster)
2234     {
2235         return 0; // complete match with existing record
2236     }
2237
2238     {
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')
2242         {
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));
2249         }
2250     }
2251
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);
2255
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);
2260
2261     ingest_nmem = nmem_create();
2262     if (se->rank)
2263     {
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);
2267     }
2268
2269     // now parsing XML record and adding data to cluster or record metadata
2270     for (n = root->children; n; n = n->next)
2271     {
2272         if (n->type != XML_ELEMENT_NODE)
2273             continue;
2274         if (!strcmp((const char *) n->name, "metadata"))
2275         {
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;
2285             xmlChar *value0;
2286
2287             type = yaz_xml_get_prop(n, "type");
2288             if (!type)
2289                 continue;
2290
2291             md_field_id
2292                 = conf_service_metadata_field_id(service, (const char *) type);
2293             if (md_field_id < 0)
2294                 continue;
2295
2296             ser_md = &service->metadata[md_field_id];
2297
2298             if (ser_md->sortkey_offset >= 0)
2299             {
2300                 sk_field_id = ser_md->sortkey_offset;
2301                 ser_sk = &service->sortkeys[sk_field_id];
2302             }
2303
2304             wrbuf_rewind(wrbuf_disp);
2305             wrbuf_rewind(wrbuf_norm);
2306
2307             value0 = xmlNodeListGetString(xdoc, n->children, 1);
2308             if (!value0 || !*value0)
2309             {
2310                 if (value0)
2311                     xmlFree(value0);
2312                 continue;
2313             }
2314
2315             if (ser_md->icurule)
2316             {
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),
2324                                               ser_md->type, 0);
2325             }
2326             else
2327             {
2328                 wrbuf_puts(wrbuf_disp, (const char *) value0);
2329                 rec_md = record_metadata_init(se->nmem, wrbuf_cstr(wrbuf_disp),
2330                                               0,
2331                                               ser_md->type, 0);
2332             }
2333
2334             xmlFree(value0);
2335
2336             // see if the field was not in cluster already (from beginning)
2337             if (!rec_md)
2338                 continue;
2339
2340             if (rank_num)
2341             {
2342                 int i;
2343                 for (i = 0; i < rank_num; i++)
2344                 {
2345                     const char *val = rank_values[i];
2346                     const char *cp = strchr(val, '=');
2347                     if (!cp)
2348                         continue;
2349                     if ((cp - val) == strlen((const char *) type)
2350                         && !memcmp(val, type, cp - val))
2351                     {
2352                         rank = cp + 1;
2353                         break;
2354                     }
2355                 }
2356             }
2357             else
2358             {
2359                 xml_rank = yaz_xml_get_prop(n, "rank");
2360                 rank = xml_rank ? (const char *) xml_rank : ser_md->rank;
2361             }
2362
2363             wheretoput = &cluster->metadata[md_field_id];
2364
2365             if (ser_md->merge == Metadata_merge_first)
2366             {
2367                 if (!metadata0[md_field_id])
2368                 {
2369                     while (*wheretoput)
2370                         wheretoput = &(*wheretoput)->next;
2371                     *wheretoput = rec_md;
2372                 }
2373             }
2374             else if (ser_md->merge == Metadata_merge_unique)
2375             {
2376                 while (*wheretoput)
2377                 {
2378                     if (!strcmp((const char *) (*wheretoput)->data.text.norm,
2379                                 rec_md->data.text.norm))
2380                         break;
2381                     wheretoput = &(*wheretoput)->next;
2382                 }
2383                 if (!*wheretoput)
2384                     *wheretoput = rec_md;
2385             }
2386             else if (ser_md->merge == Metadata_merge_longest)
2387             {
2388                 if (!*wheretoput
2389                     || strlen(rec_md->data.text.norm)
2390                     > strlen((*wheretoput)->data.text.norm))
2391                 {
2392                     *wheretoput = rec_md;
2393                     if (ser_sk)
2394                     {
2395                         pp2_charset_token_t prt;
2396                         const char *sort_str = 0;
2397                         int skip_article =
2398                             ser_sk->type == Metadata_type_skiparticle;
2399
2400                         if (!cluster->sortkeys[sk_field_id])
2401                             cluster->sortkeys[sk_field_id] =
2402                                 nmem_malloc(se->nmem,
2403                                             sizeof(union data_types));
2404
2405                         prt =
2406                             pp2_charset_token_create(service->charsets, "sort");
2407
2408                         pp2_charset_token_first(prt, rec_md->data.text.disp,
2409                                                 skip_article);
2410
2411                         pp2_charset_token_next(prt);
2412
2413                         sort_str = pp2_get_sort(prt);
2414
2415                         cluster->sortkeys[sk_field_id]->text.disp =
2416                             rec_md->data.text.disp;
2417                         if (!sort_str)
2418                         {
2419                             sort_str = rec_md->data.text.disp;
2420                             session_log(se, YLOG_WARN,
2421                                     "Could not make sortkey. Bug #1858");
2422                         }
2423                         cluster->sortkeys[sk_field_id]->text.sort =
2424                             nmem_strdup(se->nmem, sort_str);
2425                         pp2_charset_token_destroy(prt);
2426                     }
2427                 }
2428             }
2429             else if (ser_md->merge == Metadata_merge_all)
2430             {
2431                 while (*wheretoput)
2432                     wheretoput = &(*wheretoput)->next;
2433                 *wheretoput = rec_md;
2434             }
2435             else if (ser_md->merge == Metadata_merge_range)
2436             {
2437                 if (!*wheretoput)
2438                 {
2439                     *wheretoput = rec_md;
2440                     if (ser_sk)
2441                         cluster->sortkeys[sk_field_id]
2442                             = &rec_md->data;
2443                 }
2444                 else
2445                 {
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;
2452                 }
2453             }
2454
2455             // ranking of _all_ fields enabled ...
2456             if (rank)
2457             {
2458                 relevance_countwords(se->relevance, cluster,
2459                                      wrbuf_cstr(wrbuf_disp),
2460                                      rank, ser_md->name);
2461             }
2462             // construct facets ... unless the client already has reported them
2463             if (ser_md->termlist && !client_has_facet(cl, (char *) type))
2464             {
2465                 if (ser_md->type == Metadata_type_year)
2466                 {
2467                     char year[64];
2468                     sprintf(year, "%d", rec_md->data.number.max);
2469
2470                     add_facet(se, (char *) type, year, term_factor, cl);
2471                     if (rec_md->data.number.max != rec_md->data.number.min)
2472                     {
2473                         sprintf(year, "%d", rec_md->data.number.min);
2474                         add_facet(se, (char *) type, year, term_factor, cl);
2475                     }
2476                 }
2477                 else
2478                     add_facet(se, type, wrbuf_cstr(wrbuf_disp), term_factor, cl);
2479             }
2480         }
2481         else
2482         {
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++;
2487         }
2488     }
2489     nmem_destroy(ingest_nmem);
2490     xfree(metadata0);
2491     relevance_donerecord(se->relevance, cluster);
2492     se->total_records++;
2493
2494     return 0;
2495 }
2496
2497 void session_log(struct session *s, int level, const char *fmt, ...)
2498 {
2499     char buf[1024];
2500     va_list ap;
2501     va_start(ap, fmt);
2502
2503     yaz_vsnprintf(buf, sizeof(buf)-30, fmt, ap);
2504     yaz_log(level, "Session %u: %s", s ? s->session_id : 0, buf);
2505
2506     va_end(ap);
2507 }
2508
2509 /*
2510  * Local variables:
2511  * c-basic-offset: 4
2512  * c-file-style: "Stroustrup"
2513  * indent-tabs-mode: nil
2514  * End:
2515  * vim: shiftwidth=4 tabstop=8 expandtab
2516  */
2517