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