Avoid session lock while client search is initiated
[pazpar2-moved-to-github.git] / src / session.c
1 /* This file is part of Pazpar2.
2    Copyright (C) 2006-2011 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/gettimeofday.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 #define TERMLIST_HIGH_SCORE 25
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 struct session_sorted_results {
99     const char *field;
100     int increasing;
101     struct session_sorted_results *next;
102 };
103
104 /* session counting (1) , disable client counting (0) */
105 static YAZ_MUTEX g_session_mutex = 0;
106 static int no_sessions = 0;
107 static int no_session_total = 0;
108
109 static int session_use(int delta)
110 {
111     int sessions;
112     if (!g_session_mutex)
113         yaz_mutex_create(&g_session_mutex);
114     yaz_mutex_enter(g_session_mutex);
115     no_sessions += delta;
116     if (delta > 0)
117         no_session_total += delta;
118     sessions = no_sessions;
119     yaz_mutex_leave(g_session_mutex);
120     yaz_log(YLOG_DEBUG, "%s sessions=%d", delta == 0 ? "" : (delta > 0 ? "INC" : "DEC"), no_sessions);
121     return sessions;
122 }
123
124 int sessions_count(void)
125 {
126     return session_use(0);
127 }
128
129 int session_count_total(void)
130 {
131     int total = 0;
132     if (!g_session_mutex)
133         return 0;
134     yaz_mutex_enter(g_session_mutex);
135     total = no_session_total;
136     yaz_mutex_leave(g_session_mutex);
137     return total;
138 }
139
140 static void log_xml_doc(xmlDoc *doc)
141 {
142     FILE *lf = yaz_log_file();
143     xmlChar *result = 0;
144     int len = 0;
145 #if LIBXML_VERSION >= 20600
146     xmlDocDumpFormatMemory(doc, &result, &len, 1);
147 #else
148     xmlDocDumpMemory(doc, &result, &len);
149 #endif
150     if (lf && len)
151     {
152         (void) fwrite(result, 1, len, lf);
153         fprintf(lf, "\n");
154     }
155     xmlFree(result);
156 }
157
158 static void session_enter(struct session *s)
159 {
160     yaz_mutex_enter(s->session_mutex);
161 }
162
163 static void session_leave(struct session *s)
164 {
165     yaz_mutex_leave(s->session_mutex);
166 }
167
168 void add_facet(struct session *s, const char *type, const char *value, int count)
169 {
170     struct conf_service *service = s->service;
171     pp2_charset_token_t prt;
172     const char *facet_component;
173     WRBUF facet_wrbuf = wrbuf_alloc();
174     WRBUF display_wrbuf = wrbuf_alloc();
175     int i;
176     const char *icu_chain_id = 0;
177
178     for (i = 0; i < service->num_metadata; i++)
179         if (!strcmp((service->metadata + i)->name, type))
180             icu_chain_id = (service->metadata + i)->facetrule;
181     if (!icu_chain_id)
182         icu_chain_id = "facet";
183     prt = pp2_charset_token_create(service->charsets, icu_chain_id);
184     if (!prt)
185     {
186         yaz_log(YLOG_FATAL, "Unknown ICU chain '%s' for facet of type '%s'",
187                 icu_chain_id, type);
188         wrbuf_destroy(facet_wrbuf);
189         wrbuf_destroy(display_wrbuf);
190         return;
191     }
192     pp2_charset_token_first(prt, value, 0);
193     while ((facet_component = pp2_charset_token_next(prt)))
194     {
195         const char *display_component;
196         if (*facet_component)
197         {
198             if (wrbuf_len(facet_wrbuf))
199                 wrbuf_puts(facet_wrbuf, " ");
200             wrbuf_puts(facet_wrbuf, facet_component);
201         }
202         display_component = pp2_get_display(prt);
203         if (display_component)
204         {
205             if (wrbuf_len(display_wrbuf))
206                 wrbuf_puts(display_wrbuf, " ");
207             wrbuf_puts(display_wrbuf, display_component);
208         }
209     }
210     pp2_charset_token_destroy(prt);
211  
212     if (wrbuf_len(facet_wrbuf))
213     {
214         int i;
215         for (i = 0; i < s->num_termlists; i++)
216             if (!strcmp(s->termlists[i].name, type))
217                 break;
218         if (i == s->num_termlists)
219         {
220             if (i == SESSION_MAX_TERMLISTS)
221             {
222                 session_log(s, YLOG_FATAL, "Too many termlists");
223                 wrbuf_destroy(facet_wrbuf);
224                 wrbuf_destroy(display_wrbuf);
225                 return;
226             }
227             
228             s->termlists[i].name = nmem_strdup(s->nmem, type);
229             s->termlists[i].termlist 
230                 = termlist_create(s->nmem, TERMLIST_HIGH_SCORE);
231             s->num_termlists = i + 1;
232         }
233         
234 #if 0
235         session_log(s, YLOG_DEBUG, "Facets for %s: %s norm:%s (%d)", type, value, wrbuf_cstr(facet_wrbuf), count);
236 #endif
237         termlist_insert(s->termlists[i].termlist, wrbuf_cstr(display_wrbuf),
238                         wrbuf_cstr(facet_wrbuf), count);
239     }
240     wrbuf_destroy(facet_wrbuf);
241     wrbuf_destroy(display_wrbuf);
242 }
243
244 static xmlDoc *record_to_xml(struct session *se,
245                              struct session_database *sdb, const char *rec)
246 {
247     struct database *db = sdb->database;
248     xmlDoc *rdoc = 0;
249
250     rdoc = xmlParseMemory(rec, strlen(rec));
251
252     if (!rdoc)
253     {
254         session_log(se, YLOG_FATAL, "Non-wellformed XML received from %s",
255                     db->id);
256         return 0;
257     }
258
259     if (global_parameters.dump_records)
260     {
261         session_log(se, YLOG_LOG, "Un-normalized record from %s", db->id);
262         log_xml_doc(rdoc);
263     }
264
265     return rdoc;
266 }
267
268 #define MAX_XSLT_ARGS 16
269
270 // Add static values from session database settings if applicable
271 static void insert_settings_parameters(struct session_database *sdb,
272                                        struct conf_service *service,
273                                        char **parms,
274                                        NMEM nmem)
275 {
276     int i;
277     int nparms = 0;
278     int offset = 0;
279
280     for (i = 0; i < service->num_metadata; i++)
281     {
282         struct conf_metadata *md = &service->metadata[i];
283         int setting;
284
285         if (md->setting == Metadata_setting_parameter &&
286             (setting = settings_lookup_offset(service, md->name)) >= 0)
287         {
288             const char *val = session_setting_oneval(sdb, setting);
289             if (val && nparms < MAX_XSLT_ARGS)
290             {
291                 char *buf;
292                 int len = strlen(val);
293                 buf = nmem_malloc(nmem, len + 3);
294                 buf[0] = '\'';
295                 strcpy(buf + 1, val);
296                 buf[len+1] = '\'';
297                 buf[len+2] = '\0';
298                 parms[offset++] = md->name;
299                 parms[offset++] = buf;
300                 nparms++;
301             }
302         }
303     }
304     parms[offset] = 0;
305 }
306
307 // Add static values from session database settings if applicable
308 static void insert_settings_values(struct session_database *sdb, xmlDoc *doc,
309     struct conf_service *service)
310 {
311     int i;
312
313     for (i = 0; i < service->num_metadata; i++)
314     {
315         struct conf_metadata *md = &service->metadata[i];
316         int offset;
317
318         if (md->setting == Metadata_setting_postproc &&
319             (offset = settings_lookup_offset(service, md->name)) >= 0)
320         {
321             const char *val = session_setting_oneval(sdb, offset);
322             if (val)
323             {
324                 xmlNode *r = xmlDocGetRootElement(doc);
325                 xmlNode *n = xmlNewTextChild(r, 0, (xmlChar *) "metadata",
326                                              (xmlChar *) val);
327                 xmlSetProp(n, (xmlChar *) "type", (xmlChar *) md->name);
328             }
329         }
330     }
331 }
332
333 static xmlDoc *normalize_record(struct session *se,
334                                 struct session_database *sdb,
335                                 struct conf_service *service,
336                                 const char *rec, NMEM nmem)
337 {
338     xmlDoc *rdoc = record_to_xml(se, sdb, rec);
339
340     if (rdoc)
341     {
342         char *parms[MAX_XSLT_ARGS*2+1];
343         
344         insert_settings_parameters(sdb, service, parms, nmem);
345         
346         if (normalize_record_transform(sdb->map, &rdoc, (const char **)parms))
347         {
348             session_log(se, YLOG_WARN, "Normalize failed from %s",
349                         sdb->database->id);
350         }
351         else
352         {
353             insert_settings_values(sdb, rdoc, service);
354             
355             if (global_parameters.dump_records)
356             {
357                 session_log(se, YLOG_LOG, "Normalized record from %s", 
358                             sdb->database->id);
359                 log_xml_doc(rdoc);
360             }
361         }
362     }
363     return rdoc;
364 }
365
366 void session_settings_dump(struct session *se,
367                            struct session_database *db,
368                            WRBUF w)
369 {
370     if (db->settings)
371     {
372         int i, num = db->num_settings;
373         for (i = 0; i < num; i++)
374         {
375             struct setting *s = db->settings[i];
376             for (;s ; s = s->next)
377             {
378                 wrbuf_puts(w, "<set name=\"");
379                 wrbuf_xmlputs(w, s->name);
380                 wrbuf_puts(w, "\" value=\"");
381                 wrbuf_xmlputs(w, s->value);
382                 wrbuf_puts(w, "\"/>");
383             }
384             if (db->settings[i])
385                 wrbuf_puts(w, "\n");
386         }
387     }
388 }
389
390 // Retrieve first defined value for 'name' for given database.
391 // Will be extended to take into account user associated with session
392 const char *session_setting_oneval(struct session_database *db, int offset)
393 {
394     if (offset >= db->num_settings || !db->settings[offset])
395         return "";
396     return db->settings[offset]->value;
397 }
398
399 // Prepare XSLT stylesheets for record normalization
400 // Structures are allocated on the session_wide nmem to avoid having
401 // to recompute this for every search. This would lead
402 // to leaking if a single session was to repeatedly change the PZ_XSLT
403 // setting. However, this is not a realistic use scenario.
404 static int prepare_map(struct session *se, struct session_database *sdb)
405 {
406     const char *s;
407
408     if (sdb->settings && sdb->settings[PZ_XSLT] && !sdb->map &&
409         (s = session_setting_oneval(sdb, PZ_XSLT)))        
410     {
411         char auto_stylesheet[256];
412
413         if (!strcmp(s, "auto"))
414         {
415             const char *request_syntax = session_setting_oneval(
416                 sdb, PZ_REQUESTSYNTAX);
417             if (request_syntax)
418             {
419                 char *cp;
420                 yaz_snprintf(auto_stylesheet, sizeof(auto_stylesheet),
421                              "%s.xsl", request_syntax);
422                 for (cp = auto_stylesheet; *cp; cp++)
423                 {
424                     /* deliberately only consider ASCII */
425                     if (*cp > 32 && *cp < 127)
426                         *cp = tolower(*cp);
427                 }
428                 s = auto_stylesheet;
429             }
430             else
431             {
432                 session_log(se, YLOG_WARN,
433                             "No pz:requestsyntax for auto stylesheet");
434             }
435         }
436         sdb->map = normalize_cache_get(se->normalize_cache,
437                                        se->service, s);
438         if (!sdb->map)
439             return -1;
440     }
441     return 0;
442 }
443
444 // called if watch should be removed because http_channel is to be destroyed
445 static void session_watch_cancel(void *data, struct http_channel *c,
446                                  void *data2)
447 {
448     struct session_watchentry *ent = data;
449
450     ent->fun = 0;
451     ent->data = 0;
452     ent->obs = 0;
453 }
454
455 // set watch. Returns 0=OK, -1 if watch is already set
456 int session_set_watch(struct session *s, int what, 
457                       session_watchfun fun, void *data,
458                       struct http_channel *chan)
459 {
460     int ret;
461     session_enter(s);
462     if (s->watchlist[what].fun)
463         ret = -1;
464     else
465     {
466         
467         s->watchlist[what].fun = fun;
468         s->watchlist[what].data = data;
469         s->watchlist[what].obs = http_add_observer(chan, &s->watchlist[what],
470                                                    session_watch_cancel);
471         ret = 0;
472     }
473     session_leave(s);
474     return ret;
475 }
476
477 void session_alert_watch(struct session *s, int what)
478 {
479     assert(s);
480     session_enter(s);
481     if (s->watchlist[what].fun)
482     {
483         /* our watch is no longer associated with http_channel */
484         void *data;
485         session_watchfun fun;
486
487         http_remove_observer(s->watchlist[what].obs);
488         fun  = s->watchlist[what].fun;
489         data = s->watchlist[what].data;
490
491         /* reset watch before fun is invoked - in case fun wants to set
492            it again */
493         s->watchlist[what].fun = 0;
494         s->watchlist[what].data = 0;
495         s->watchlist[what].obs = 0;
496
497         session_leave(s);
498         session_log(s, YLOG_DEBUG,
499                     "Alert Watch: %d calling function: %p", what, fun);
500         fun(data);
501     }
502     else
503         session_leave(s);
504 }
505
506 //callback for grep_databases
507 static void select_targets_callback(struct session *se,
508                                     struct session_database *db)
509 {
510     struct client *cl;
511     struct client_list *l;
512
513     for (l = se->clients_cached; l; l = l->next)
514         if (client_get_database(l->client) == db)
515             break;
516
517     if (l)
518         cl = l->client;
519     else
520     {
521         cl = client_create(db->database->id);
522         client_set_database(cl, db);
523         client_set_session(cl, se);
524
525         l = xmalloc(sizeof(*l));
526         l->client = cl;
527         l->next = se->clients_cached;
528         se->clients_cached = l;
529     }
530
531     l = xmalloc(sizeof(*l));
532     l->client = cl;
533     l->next = se->clients_active;
534     se->clients_active = l;
535 }
536
537 static void session_reset_active_clients(struct session *se,
538                                          struct client_list *new_list)
539 {
540     struct client_list *l;
541
542     session_enter(se);
543     l = se->clients_active;
544     se->clients_active = new_list;
545     session_leave(se);
546
547     while (l)
548     {
549         struct client_list *l_next = l->next;
550         xfree(l);
551         l = l_next;
552     }
553 }
554
555 static void session_remove_cached_clients(struct session *se)
556 {
557     struct client_list *l;
558
559     session_reset_active_clients(se, 0);
560
561     session_enter(se);
562     l = se->clients_cached;
563     se->clients_cached = 0;
564     session_leave(se);
565
566     while (l)
567     {
568         struct client_list *l_next = l->next;
569         client_lock(l->client);
570         client_set_session(l->client, 0);
571         client_set_database(l->client, 0);
572         client_unlock(l->client);
573         client_destroy(l->client);
574         xfree(l);
575         l = l_next;
576     }
577 }
578
579 // Associates a set of clients with a session;
580 // Note: Session-databases represent databases with per-session 
581 // setting overrides
582 static int select_targets(struct session *se, const char *filter)
583 {
584     return session_grep_databases(se, filter, select_targets_callback);
585 }
586
587 int session_active_clients(struct session *s)
588 {
589     struct client_list *l;
590     int res = 0;
591
592     for (l = s->clients_active; l; l = l->next)
593         if (client_is_active(l->client))
594             res++;
595
596     return res;
597 }
598
599 int session_is_preferred_clients_ready(struct session *s)
600 {
601     struct client_list *l;
602     int res = 0;
603
604     for (l = s->clients_active; l; l = l->next)
605         if (client_is_active_preferred(l->client))
606             res++;
607     session_log(s, YLOG_DEBUG, "Has %d active preferred clients.", res);
608     return res == 0;
609 }
610
611 static const char *get_strategy_plus_sort(struct client *l, const char *field)
612 {
613     struct session_database *sdb = client_get_database(l);
614     struct setting *s;
615
616     const char *strategy_plus_sort = 0;
617     
618     for (s = sdb->settings[PZ_SORTMAP]; s; s = s->next)
619     {
620         char *p = strchr(s->name + 3, ':');
621         if (!p)
622         {
623             yaz_log(YLOG_WARN, "Malformed sortmap name: %s", s->name);
624             continue;
625         }
626         p++;
627         if (!strcmp(p, field))
628         {
629             strategy_plus_sort = s->value;
630             break;
631         }
632     }
633     return strategy_plus_sort;
634 }
635
636 void session_sort(struct session *se, const char *field, int increasing)
637 {
638     struct session_sorted_results *sr;
639     struct client_list *l;
640
641     session_enter(se);
642
643     /* see if we already have sorted for this critieria */
644     for (sr = se->sorted_results; sr; sr = sr->next)
645     {
646         if (!strcmp(field, sr->field) && increasing == sr->increasing)
647             break;
648     }
649     if (sr)
650     {
651         yaz_log(YLOG_LOG, "search_sort: field=%s increasing=%d already fetched",
652                 field, increasing);
653         session_leave(se);
654         return;
655     }
656     yaz_log(YLOG_LOG, "search_sort: field=%s increasing=%d must fetch",
657             field, increasing);
658     sr = nmem_malloc(se->nmem, sizeof(*sr));
659     sr->field = nmem_strdup(se->nmem, field);
660     sr->increasing = increasing;
661     sr->next = se->sorted_results;
662     se->sorted_results = sr;
663     
664     for (l = se->clients_active; l; l = l->next)
665     {
666         struct client *cl = l->client;
667         const char *strategy_plus_sort = get_strategy_plus_sort(cl, field);
668         if (strategy_plus_sort)
669         {
670             struct timeval tval;
671             if (client_prep_connection(cl, se->service->z3950_operation_timeout,
672                                        se->service->z3950_session_timeout,
673                                        se->service->server->iochan_man,
674                                        &tval))
675                 client_start_search(cl, strategy_plus_sort, increasing);
676         }
677     }
678     session_leave(se);
679 }
680
681 enum pazpar2_error_code session_search(struct session *se,
682                                        const char *query,
683                                        const char *startrecs,
684                                        const char *maxrecs,
685                                        const char *filter,
686                                        const char *limit,
687                                        const char **addinfo,
688                                        const char *sort_field, int increasing)
689 {
690     int live_channels = 0;
691     int no_working = 0;
692     int no_failed = 0;
693     struct client_list *l, *l0;
694     struct timeval tval;
695     facet_limits_t facet_limits;
696
697     session_log(se, YLOG_DEBUG, "Search");
698
699     *addinfo = 0;
700
701     if (se->settings_modified)
702         session_remove_cached_clients(se);
703     else
704         session_reset_active_clients(se, 0);
705     
706     session_enter(se);
707     reclist_destroy(se->reclist);
708     se->reclist = 0;
709     se->settings_modified = 0;
710     relevance_destroy(&se->relevance);
711     nmem_reset(se->nmem);
712     se->total_records = se->total_merged = 0;
713     se->num_termlists = 0;
714
715     /* reset list of sorted results and clear to relevance search */
716     se->sorted_results = nmem_malloc(se->nmem, sizeof(*se->sorted_results));
717     se->sorted_results->field = nmem_strdup(se->nmem, sort_field);
718     se->sorted_results->increasing = increasing;
719     se->sorted_results->next = 0;
720     
721     live_channels = select_targets(se, filter);
722     if (!live_channels)
723     {
724         session_leave(se);
725         return PAZPAR2_NO_TARGETS;
726     }
727     se->reclist = reclist_create(se->nmem);
728
729     yaz_gettimeofday(&tval);
730     
731     tval.tv_sec += 5;
732
733     facet_limits = facet_limits_create(limit);
734     if (!facet_limits)
735     {
736         *addinfo = "limit";
737         session_leave(se);
738         return PAZPAR2_MALFORMED_PARAMETER_VALUE;
739     }
740
741     l0 = se->clients_active;
742     se->clients_active = 0;
743     session_leave(se);
744
745     for (l = l0; l; l = l->next)
746     {
747         int parse_ret;
748         struct client *cl = l->client;
749         const char *strategy_plus_sort = get_strategy_plus_sort(cl, sort_field);
750
751         if (prepare_map(se, client_get_database(cl)) < 0)
752             continue;
753
754         parse_ret = client_parse_query(cl, query, facet_limits, startrecs,
755             maxrecs);
756         if (parse_ret < 0)
757             no_failed++;
758         else if (parse_ret == 0)
759         {
760             session_log(se, YLOG_LOG, "client NEW %s", client_get_id(cl));
761             no_working++;
762             if (client_prep_connection(cl, se->service->z3950_operation_timeout,
763                                        se->service->z3950_session_timeout,
764                                        se->service->server->iochan_man,
765                                        &tval))
766                 client_start_search(cl, strategy_plus_sort, increasing);
767         }
768         else
769         {
770             session_log(se, YLOG_LOG, "client REUSE %s", client_get_id(cl));
771             no_working++;
772             if (client_prep_connection(cl, se->service->z3950_operation_timeout,
773                                        se->service->z3950_session_timeout,
774                                        se->service->server->iochan_man,
775                                        &tval))
776             {
777                 client_reingest(cl);
778             }
779         }
780     }
781     facet_limits_destroy(facet_limits);
782     session_reset_active_clients(se, l0);
783
784     if (no_working == 0)
785     {
786         if (no_failed > 0)
787         {
788             *addinfo = "query";
789             return PAZPAR2_MALFORMED_PARAMETER_VALUE;
790         }
791         else
792             return PAZPAR2_NO_TARGETS;
793     }
794     yaz_log(YLOG_LOG, "session_start_search done");
795     return PAZPAR2_NO_ERROR;
796 }
797
798 // Creates a new session_database object for a database
799 static void session_init_databases_fun(void *context, struct database *db)
800 {
801     struct session *se = (struct session *) context;
802     struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
803     int i;
804
805     new->database = db;
806     
807     new->map = 0;
808     assert(db->settings);
809     new->settings = nmem_malloc(se->session_nmem,
810                                 sizeof(struct settings *) * db->num_settings);
811     new->num_settings = db->num_settings;
812     for (i = 0; i < db->num_settings; i++)
813     {
814         struct setting *setting = db->settings[i];
815         new->settings[i] = setting;
816     }
817     new->next = se->databases;
818     se->databases = new;
819 }
820
821 // Doesn't free memory associated with sdb -- nmem takes care of that
822 static void session_database_destroy(struct session_database *sdb)
823 {
824     sdb->map = 0;
825 }
826
827 // Initialize session_database list -- this represents this session's view
828 // of the database list -- subject to modification by the settings ws command
829 void session_init_databases(struct session *se)
830 {
831     se->databases = 0;
832     predef_grep_databases(se, se->service, session_init_databases_fun);
833 }
834
835 // Probably session_init_databases_fun should be refactored instead of
836 // called here.
837 static struct session_database *load_session_database(struct session *se, 
838                                                       char *id)
839 {
840     struct database *db = new_database(id, se->session_nmem);
841
842     session_init_databases_fun((void*) se, db);
843
844     // New sdb is head of se->databases list
845     return se->databases;
846 }
847
848 // Find an existing session database. If not found, load it
849 static struct session_database *find_session_database(struct session *se, 
850                                                       char *id)
851 {
852     struct session_database *sdb;
853
854     for (sdb = se->databases; sdb; sdb = sdb->next)
855         if (!strcmp(sdb->database->id, id))
856             return sdb;
857     return load_session_database(se, id);
858 }
859
860 // Apply a session override to a database
861 void session_apply_setting(struct session *se, char *dbname, char *setting,
862                            char *value)
863 {
864     struct session_database *sdb = find_session_database(se, dbname);
865     struct conf_service *service = se->service;
866     struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
867     int offset = settings_create_offset(service, setting);
868
869     expand_settings_array(&sdb->settings, &sdb->num_settings, offset,
870                           se->session_nmem);
871     new->precedence = 0;
872     new->target = dbname;
873     new->name = setting;
874     new->value = value;
875     new->next = sdb->settings[offset];
876     sdb->settings[offset] = new;
877
878     se->settings_modified = 1;
879
880     // Force later recompute of settings-driven data structures
881     // (happens when a search starts and client connections are prepared)
882     switch (offset)
883     {
884     case PZ_XSLT:
885         if (sdb->map)
886         {
887             sdb->map = 0;
888         }
889         break;
890     }
891 }
892
893 void session_destroy(struct session *se)
894 {
895     struct session_database *sdb;
896     session_log(se, YLOG_DEBUG, "Destroying");
897     session_use(-1);
898     session_remove_cached_clients(se);
899
900     for (sdb = se->databases; sdb; sdb = sdb->next)
901         session_database_destroy(sdb);
902     normalize_cache_destroy(se->normalize_cache);
903     relevance_destroy(&se->relevance);
904     reclist_destroy(se->reclist);
905     nmem_destroy(se->nmem);
906     service_destroy(se->service);
907     yaz_mutex_destroy(&se->session_mutex);
908 }
909
910 size_t session_get_memory_status(struct session *session) {
911     size_t session_nmem;
912     if (session == 0)
913         return 0;
914     session_enter(session);
915     session_nmem = nmem_total(session->nmem);
916     session_leave(session);
917     return session_nmem;
918 }
919
920
921 struct session *new_session(NMEM nmem, struct conf_service *service,
922                             unsigned session_id)
923 {
924     int i;
925     struct session *session = nmem_malloc(nmem, sizeof(*session));
926
927     char tmp_str[50];
928
929     sprintf(tmp_str, "session#%u", session_id);
930
931     session->session_id = session_id;
932     session_log(session, YLOG_DEBUG, "New");
933     session->service = service;
934     session->relevance = 0;
935     session->total_records = 0;
936     session->number_of_warnings_unknown_elements = 0;
937     session->number_of_warnings_unknown_metadata = 0;
938     session->num_termlists = 0;
939     session->reclist = 0;
940     session->clients_active = 0;
941     session->clients_cached = 0;
942     session->settings_modified = 0;
943     session->session_nmem = nmem;
944     session->nmem = nmem_create();
945     session->databases = 0;
946     for (i = 0; i <= SESSION_WATCH_MAX; i++)
947     {
948         session->watchlist[i].data = 0;
949         session->watchlist[i].fun = 0;
950     }
951     session->normalize_cache = normalize_cache_create();
952     session->session_mutex = 0;
953     pazpar2_mutex_create(&session->session_mutex, tmp_str);
954     session_use(1);
955     return session;
956 }
957
958 const char * client_get_suggestions_xml(struct client *cl, WRBUF wrbuf);
959
960 static struct hitsbytarget *hitsbytarget_nb(struct session *se,
961                                             int *count, NMEM nmem)
962 {
963     struct hitsbytarget *res = 0;
964     struct client_list *l;
965     size_t sz = 0;
966
967     for (l = se->clients_active; l; l = l->next)
968         sz++;
969
970     res = nmem_malloc(nmem, sizeof(*res) * sz);
971     *count = 0;
972     for (l = se->clients_active; l; l = l->next)
973     {
974         struct client *cl = l->client;
975         WRBUF w = wrbuf_alloc();
976         const char *name = session_setting_oneval(client_get_database(cl),
977                                                   PZ_NAME);
978
979         res[*count].id = client_get_id(cl);
980         res[*count].name = *name ? name : "Unknown";
981         res[*count].hits = client_get_hits(cl);
982         res[*count].records = client_get_num_records(cl);
983         res[*count].diagnostic = client_get_diagnostic(cl);
984         res[*count].state = client_get_state_str(cl);
985         res[*count].connected  = client_get_connection(cl) ? 1 : 0;
986         session_settings_dump(se, client_get_database(cl), w);
987         res[*count].settings_xml = nmem_strdup(nmem, wrbuf_cstr(w));
988         wrbuf_rewind(w);
989         wrbuf_puts(w, "");
990         res[*count].suggestions_xml = nmem_strdup(nmem, client_get_suggestions_xml(cl, w));
991         wrbuf_destroy(w);
992         (*count)++;
993     }
994     return res;
995 }
996
997 struct hitsbytarget *get_hitsbytarget(struct session *se, int *count, NMEM nmem)
998 {
999     struct hitsbytarget *p;
1000     session_enter(se);
1001     p = hitsbytarget_nb(se, count, nmem);
1002     session_leave(se);
1003     return p;
1004 }
1005     
1006 struct termlist_score **get_termlist_score(struct session *se,
1007                                            const char *name, int *num)
1008 {
1009     int i;
1010     struct termlist_score **tl = 0;
1011
1012     session_enter(se);
1013     for (i = 0; i < se->num_termlists; i++)
1014         if (!strcmp((const char *) se->termlists[i].name, name))
1015         {
1016             tl = termlist_highscore(se->termlists[i].termlist, num);
1017             break;
1018         }
1019     session_leave(se);
1020     return tl;
1021 }
1022
1023 // Compares two hitsbytarget nodes by hitcount
1024 static int cmp_ht(const void *p1, const void *p2)
1025 {
1026     const struct hitsbytarget *h1 = p1;
1027     const struct hitsbytarget *h2 = p2;
1028     return h2->hits - h1->hits;
1029 }
1030
1031 static int targets_termlist_nb(WRBUF wrbuf, struct session *se, int num,
1032                                NMEM nmem)
1033 {
1034     struct hitsbytarget *ht;
1035     int count, i;
1036
1037     ht = hitsbytarget_nb(se, &count, nmem);
1038     qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht);
1039     for (i = 0; i < count && i < num && ht[i].hits > 0; i++)
1040     {
1041
1042         // do only print terms which have display names
1043     
1044         wrbuf_puts(wrbuf, "<term>\n");
1045
1046         wrbuf_puts(wrbuf, "<id>");
1047         wrbuf_xmlputs(wrbuf, ht[i].id);
1048         wrbuf_puts(wrbuf, "</id>\n");
1049         
1050         wrbuf_puts(wrbuf, "<name>");
1051         if (!ht[i].name || !ht[i].name[0])
1052             wrbuf_xmlputs(wrbuf, "NO TARGET NAME");
1053         else
1054             wrbuf_xmlputs(wrbuf, ht[i].name);
1055         wrbuf_puts(wrbuf, "</name>\n");
1056         
1057         wrbuf_printf(wrbuf, "<frequency>" ODR_INT_PRINTF "</frequency>\n",
1058                      ht[i].hits);
1059         
1060         wrbuf_puts(wrbuf, "<state>");
1061         wrbuf_xmlputs(wrbuf, ht[i].state);
1062         wrbuf_puts(wrbuf, "</state>\n");
1063         
1064         wrbuf_printf(wrbuf, "<diagnostic>%d</diagnostic>\n", 
1065                      ht[i].diagnostic);
1066         wrbuf_puts(wrbuf, "</term>\n");
1067     }
1068     return count;
1069 }
1070
1071 void perform_termlist(struct http_channel *c, struct session *se,
1072                       const char *name, int num)
1073 {
1074     int i, j;
1075     NMEM nmem_tmp = nmem_create();
1076     char **names;
1077     int num_names = 0;
1078
1079     if (name)
1080         nmem_strsplit(nmem_tmp, ",", name, &names, &num_names);
1081
1082     session_enter(se);
1083
1084     for (j = 0; j < num_names; j++)
1085     {
1086         const char *tname;
1087         
1088         wrbuf_puts(c->wrbuf, "<list name=\"");
1089         wrbuf_xmlputs(c->wrbuf, names[j]);
1090         wrbuf_puts(c->wrbuf, "\">\n");
1091
1092         for (i = 0; i < se->num_termlists; i++)
1093         {
1094             tname = se->termlists[i].name;
1095             if (num_names > 0 && !strcmp(names[j], tname))
1096             {
1097                 struct termlist_score **p = 0;
1098                 int len;
1099                 p = termlist_highscore(se->termlists[i].termlist, &len);
1100                 if (p)
1101                 {
1102                     int i;
1103                     for (i = 0; i < len && i < num; i++)
1104                     {
1105                         // prevent sending empty term elements
1106                         if (!p[i]->display_term || !p[i]->display_term[0])
1107                             continue;
1108                         
1109                         wrbuf_puts(c->wrbuf, "<term>");
1110                         wrbuf_puts(c->wrbuf, "<name>");
1111                         wrbuf_xmlputs(c->wrbuf, p[i]->display_term);
1112                         wrbuf_puts(c->wrbuf, "</name>");
1113                         
1114                         wrbuf_printf(c->wrbuf, 
1115                                      "<frequency>%d</frequency>", 
1116                                      p[i]->frequency);
1117                         wrbuf_puts(c->wrbuf, "</term>\n");
1118                     }
1119                 }
1120             }
1121         }
1122         tname = "xtargets";
1123         if (num_names > 0 && !strcmp(names[j], tname))
1124         {
1125             targets_termlist_nb(c->wrbuf, se, num, c->nmem);
1126         }
1127         wrbuf_puts(c->wrbuf, "</list>\n");
1128     }
1129     session_leave(se);
1130     nmem_destroy(nmem_tmp);
1131 }
1132
1133 #ifdef MISSING_HEADERS
1134 void report_nmem_stats(void)
1135 {
1136     size_t in_use, is_free;
1137
1138     nmem_get_memory_in_use(&in_use);
1139     nmem_get_memory_free(&is_free);
1140
1141     yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld", 
1142             (long) in_use, (long) is_free);
1143 }
1144 #endif
1145
1146 struct record_cluster *show_single_start(struct session *se, const char *id,
1147                                          struct record_cluster **prev_r,
1148                                          struct record_cluster **next_r)
1149 {
1150     struct record_cluster *r = 0;
1151
1152     session_enter(se);
1153     *prev_r = 0;
1154     *next_r = 0;
1155     if (se->reclist)
1156     {
1157         reclist_enter(se->reclist);
1158         while ((r = reclist_read_record(se->reclist)))
1159         {
1160             if (!strcmp(r->recid, id))
1161             {
1162                 *next_r = reclist_read_record(se->reclist);
1163                 break;
1164             }
1165             *prev_r = r;
1166         }
1167         reclist_leave(se->reclist);
1168     }
1169     if (!r)
1170         session_leave(se);
1171     return r;
1172 }
1173
1174 void show_single_stop(struct session *se, struct record_cluster *rec)
1175 {
1176     session_leave(se);
1177 }
1178
1179 struct record_cluster **show_range_start(struct session *se,
1180                                          struct reclist_sortparms *sp, 
1181                                          int start, int *num, int *total, Odr_int *sumhits)
1182 {
1183     struct record_cluster **recs;
1184     struct reclist_sortparms *spp;
1185     int i;
1186 #if USE_TIMING    
1187     yaz_timing_t t = yaz_timing_create();
1188 #endif
1189     session_enter(se);
1190     recs = nmem_malloc(se->nmem, *num * sizeof(struct record_cluster *));
1191     if (!se->relevance)
1192     {
1193         *num = 0;
1194         *total = 0;
1195         *sumhits = 0;
1196         recs = 0;
1197     }
1198     else
1199     {
1200         struct client_list *l;
1201         
1202         for (spp = sp; spp; spp = spp->next)
1203             if (spp->type == Metadata_sortkey_relevance)
1204             {
1205                 relevance_prepare_read(se->relevance, se->reclist);
1206                 break;
1207             }
1208         reclist_sort(se->reclist, sp);
1209         
1210         reclist_enter(se->reclist);
1211         *total = reclist_get_num_records(se->reclist);
1212
1213         *sumhits = 0;
1214         for (l = se->clients_active; l; l = l->next)
1215             *sumhits += client_get_hits(l->client);
1216         
1217         for (i = 0; i < start; i++)
1218             if (!reclist_read_record(se->reclist))
1219             {
1220                 *num = 0;
1221                 recs = 0;
1222                 break;
1223             }
1224         
1225         for (i = 0; i < *num; i++)
1226         {
1227             struct record_cluster *r = reclist_read_record(se->reclist);
1228             if (!r)
1229             {
1230                 *num = i;
1231                 break;
1232             }
1233             recs[i] = r;
1234         }
1235         reclist_leave(se->reclist);
1236     }
1237 #if USE_TIMING
1238     yaz_timing_stop(t);
1239     yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f", 
1240             yaz_timing_get_real(t), yaz_timing_get_user(t),
1241             yaz_timing_get_sys(t));
1242     yaz_timing_destroy(&t);
1243 #endif
1244     return recs;
1245 }
1246
1247 void show_range_stop(struct session *se, struct record_cluster **recs)
1248 {
1249     session_leave(se);
1250 }
1251
1252 void statistics(struct session *se, struct statistics *stat)
1253 {
1254     struct client_list *l;
1255     int count = 0;
1256
1257     memset(stat, 0, sizeof(*stat));
1258     stat->num_hits = 0;
1259     for (l = se->clients_active; l; l = l->next)
1260     {
1261         struct client *cl = l->client;
1262         if (!client_get_connection(cl))
1263             stat->num_no_connection++;
1264         stat->num_hits += client_get_hits(cl);
1265         switch (client_get_state(cl))
1266         {
1267         case Client_Connecting: stat->num_connecting++; break;
1268         case Client_Working: stat->num_working++; break;
1269         case Client_Idle: stat->num_idle++; break;
1270         case Client_Failed: stat->num_failed++; break;
1271         case Client_Error: stat->num_error++; break;
1272         default: break;
1273         }
1274         count++;
1275     }
1276     stat->num_records = se->total_records;
1277
1278     stat->num_clients = count;
1279 }
1280
1281 static struct record_metadata *record_metadata_init(
1282     NMEM nmem, const char *value, enum conf_metadata_type type,
1283     struct _xmlAttr *attr)
1284 {
1285     struct record_metadata *rec_md = record_metadata_create(nmem);
1286     struct record_metadata_attr **attrp = &rec_md->attributes;
1287     
1288     for (; attr; attr = attr->next)
1289     {
1290         if (attr->children && attr->children->content)
1291         {
1292             if (strcmp((const char *) attr->name, "type"))
1293             {  /* skip the "type" attribute.. Its value is already part of
1294                   the element in output (md-%s) and so repeating it here
1295                   is redundant */
1296                 *attrp = nmem_malloc(nmem, sizeof(**attrp));
1297                 (*attrp)->name =
1298                     nmem_strdup(nmem, (const char *) attr->name);
1299                 (*attrp)->value =
1300                     nmem_strdup(nmem, (const char *) attr->children->content);
1301                 attrp = &(*attrp)->next;
1302             }
1303         }
1304     }
1305     *attrp = 0;
1306
1307     if (type == Metadata_type_generic)
1308     {
1309         char *p = nmem_strdup(nmem, value);
1310
1311         p = normalize7bit_generic(p, " ,/.:([");
1312         
1313         rec_md->data.text.disp = p;
1314         rec_md->data.text.sort = 0;
1315     }
1316     else if (type == Metadata_type_year || type == Metadata_type_date)
1317     {
1318         int first, last;
1319         int longdate = 0;
1320
1321         if (type == Metadata_type_date)
1322             longdate = 1;
1323         if (extract7bit_dates((char *) value, &first, &last, longdate) < 0)
1324             return 0;
1325
1326         rec_md->data.number.min = first;
1327         rec_md->data.number.max = last;
1328     }
1329     else
1330         return 0;
1331     return rec_md;
1332 }
1333
1334 static int get_mergekey_from_doc(xmlDoc *doc, xmlNode *root, const char *name,
1335                                  struct conf_service *service, WRBUF norm_wr)
1336 {
1337     xmlNode *n;
1338     int no_found = 0;
1339     for (n = root->children; n; n = n->next)
1340     {
1341         if (n->type != XML_ELEMENT_NODE)
1342             continue;
1343         if (!strcmp((const char *) n->name, "metadata"))
1344         {
1345             xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1346             if (type == NULL) {
1347                 yaz_log(YLOG_FATAL, "Missing type attribute on metadata element. Skipping!");
1348             }
1349             else if (!strcmp(name, (const char *) type))
1350             {
1351                 xmlChar *value = xmlNodeListGetString(doc, n->children, 1);
1352                 if (value)
1353                 {
1354                     const char *norm_str;
1355                     pp2_charset_token_t prt =
1356                         pp2_charset_token_create(service->charsets, "mergekey");
1357                     
1358                     pp2_charset_token_first(prt, (const char *) value, 0);
1359                     if (wrbuf_len(norm_wr) > 0)
1360                         wrbuf_puts(norm_wr, " ");
1361                     wrbuf_puts(norm_wr, name);
1362                     while ((norm_str =
1363                             pp2_charset_token_next(prt)))
1364                     {
1365                         if (*norm_str)
1366                         {
1367                             wrbuf_puts(norm_wr, " ");
1368                             wrbuf_puts(norm_wr, norm_str);
1369                         }
1370                     }
1371                     xmlFree(value);
1372                     pp2_charset_token_destroy(prt);
1373                     no_found++;
1374                 }
1375             }
1376             xmlFree(type);
1377         }
1378     }
1379     return no_found;
1380 }
1381
1382 static const char *get_mergekey(xmlDoc *doc, struct client *cl, int record_no,
1383                                 struct conf_service *service, NMEM nmem)
1384 {
1385     char *mergekey_norm = 0;
1386     xmlNode *root = xmlDocGetRootElement(doc);
1387     WRBUF norm_wr = wrbuf_alloc();
1388
1389     /* consider mergekey from XSL first */
1390     xmlChar *mergekey = xmlGetProp(root, (xmlChar *) "mergekey");
1391     if (mergekey)
1392     {
1393         const char *norm_str;
1394         pp2_charset_token_t prt =
1395             pp2_charset_token_create(service->charsets, "mergekey");
1396
1397         pp2_charset_token_first(prt, (const char *) mergekey, 0);
1398         while ((norm_str = pp2_charset_token_next(prt)))
1399         {
1400             if (*norm_str)
1401             {
1402                 if (wrbuf_len(norm_wr))
1403                     wrbuf_puts(norm_wr, " ");
1404                 wrbuf_puts(norm_wr, norm_str);
1405             }
1406         }
1407         pp2_charset_token_destroy(prt);
1408         xmlFree(mergekey);
1409     }
1410     else
1411     {
1412         /* no mergekey defined in XSL. Look for mergekey metadata instead */
1413         int field_id;
1414         for (field_id = 0; field_id < service->num_metadata; field_id++)
1415         {
1416             struct conf_metadata *ser_md = &service->metadata[field_id];
1417             if (ser_md->mergekey != Metadata_mergekey_no)
1418             {
1419                 int r = get_mergekey_from_doc(doc, root, ser_md->name,
1420                                               service, norm_wr);
1421                 if (r == 0 && ser_md->mergekey == Metadata_mergekey_required)
1422                 {
1423                     /* no mergekey on this one and it is required.. 
1424                        Generate unique key instead */
1425                     wrbuf_rewind(norm_wr);
1426                     break;
1427                 }
1428             }
1429         }
1430     }
1431
1432     /* generate unique key if none is not generated already or is empty */
1433     if (wrbuf_len(norm_wr) == 0)
1434     {
1435         wrbuf_printf(norm_wr, "position: %s-%d",
1436                      client_get_id(cl), record_no);
1437     }
1438     else
1439     {
1440         const char *lead = "content: ";
1441         wrbuf_insert(norm_wr, 0, lead, strlen(lead));
1442     }
1443     if (wrbuf_len(norm_wr) > 0)
1444         mergekey_norm = nmem_strdup(nmem, wrbuf_cstr(norm_wr));
1445     wrbuf_destroy(norm_wr);
1446     return mergekey_norm;
1447 }
1448
1449 /** \brief see if metadata for pz:recordfilter exists 
1450     \param root xml root element of normalized record
1451     \param sdb session database for client
1452     \retval 0 if there is no metadata for pz:recordfilter
1453     \retval 1 if there is metadata for pz:recordfilter
1454
1455     If there is no pz:recordfilter defined, this function returns 1
1456     as well.
1457 */
1458     
1459 static int check_record_filter(xmlNode *root, struct session_database *sdb)
1460 {
1461     int match = 0;
1462     xmlNode *n;
1463     const char *s;
1464     s = session_setting_oneval(sdb, PZ_RECORDFILTER);
1465
1466     if (!s || !*s)
1467         return 1;
1468
1469     for (n = root->children; n; n = n->next)
1470     {
1471         if (n->type != XML_ELEMENT_NODE)
1472             continue;
1473         if (!strcmp((const char *) n->name, "metadata"))
1474         {
1475             xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1476             if (type)
1477             {
1478                 size_t len;
1479                 int substring;
1480                 const char *eq;
1481
1482                 if ((eq = strchr(s, '=')))
1483                     substring = 0;
1484                 else if ((eq = strchr(s, '~')))
1485                     substring = 1;
1486                 if (eq)
1487                     len = eq - s;
1488                 else
1489                     len = strlen(s);
1490                 if (len == strlen((const char *)type) &&
1491                     !memcmp((const char *) type, s, len))
1492                 {
1493                     xmlChar *value = xmlNodeGetContent(n);
1494                     if (value && *value)
1495                     {
1496                         if (!eq ||
1497                             (substring && strstr((const char *) value, eq+1)) ||
1498                             (!substring && !strcmp((const char *) value, eq + 1)))
1499                             match = 1;
1500                     }
1501                     xmlFree(value);
1502                 }
1503                 xmlFree(type);
1504             }
1505         }
1506     }
1507     return match;
1508 }
1509
1510
1511 static int ingest_to_cluster(struct client *cl,
1512                              xmlDoc *xdoc,
1513                              xmlNode *root,
1514                              int record_no,
1515                              const char *mergekey_norm);
1516
1517 /** \brief ingest XML record
1518     \param cl client holds the result set for record
1519     \param rec record buffer (0 terminated)
1520     \param record_no record position (1, 2, ..)
1521     \param nmem working NMEM
1522     \retval 0 OK
1523     \retval -1 failure
1524     \retval -2 Filtered
1525 */
1526 int ingest_record(struct client *cl, const char *rec,
1527                   int record_no, NMEM nmem)
1528 {
1529     struct session *se = client_get_session(cl);
1530     int ret = 0;
1531     struct session_database *sdb = client_get_database(cl);
1532     struct conf_service *service = se->service;
1533     xmlDoc *xdoc = normalize_record(se, sdb, service, rec, nmem);
1534     xmlNode *root;
1535     const char *mergekey_norm;
1536     
1537     if (!xdoc)
1538         return -1;
1539     
1540     root = xmlDocGetRootElement(xdoc);
1541     
1542     if (!check_record_filter(root, sdb))
1543     {
1544         session_log(se, YLOG_LOG, "Filtered out record no %d from %s",
1545                     record_no, sdb->database->id);
1546         xmlFreeDoc(xdoc);
1547         return -2;
1548     }
1549     
1550     mergekey_norm = get_mergekey(xdoc, cl, record_no, service, nmem);
1551     if (!mergekey_norm)
1552     {
1553         session_log(se, YLOG_WARN, "Got no mergekey");
1554         xmlFreeDoc(xdoc);
1555         return -1;
1556     }
1557     session_enter(se);
1558     if (client_get_session(cl) == se)
1559         ingest_to_cluster(cl, xdoc, root, record_no, mergekey_norm);
1560     session_leave(se);
1561     
1562     xmlFreeDoc(xdoc);
1563     return ret;
1564 }
1565
1566 static int ingest_to_cluster(struct client *cl,
1567                              xmlDoc *xdoc,
1568                              xmlNode *root,
1569                              int record_no,
1570                              const char *mergekey_norm)
1571 {
1572     xmlNode *n;
1573     xmlChar *type = 0;
1574     xmlChar *value = 0;
1575     struct session *se = client_get_session(cl);
1576     struct conf_service *service = se->service;
1577     int term_factor = 1;
1578     struct record_cluster *cluster;
1579     struct session_database *sdb = client_get_database(cl);
1580     struct record *record = record_create(se->nmem, 
1581                                           service->num_metadata,
1582                                           service->num_sortkeys, cl,
1583                                           record_no);
1584
1585     for (n = root->children; n; n = n->next)
1586     {
1587         if (type)
1588             xmlFree(type);
1589         if (value)
1590             xmlFree(value);
1591         type = value = 0;
1592         
1593         if (n->type != XML_ELEMENT_NODE)
1594             continue;
1595         if (!strcmp((const char *) n->name, "metadata"))
1596         {
1597             struct conf_metadata *ser_md = 0;
1598             struct record_metadata **wheretoput = 0;
1599             struct record_metadata *rec_md = 0;
1600             int md_field_id = -1;
1601             
1602             type = xmlGetProp(n, (xmlChar *) "type");
1603             value = xmlNodeListGetString(xdoc, n->children, 1);
1604             
1605             if (!type || !value || !*value)
1606                 continue;
1607             
1608             md_field_id 
1609                 = conf_service_metadata_field_id(service, (const char *) type);
1610             if (md_field_id < 0)
1611             {
1612                 if (se->number_of_warnings_unknown_metadata == 0)
1613                 {
1614                     session_log(se, YLOG_WARN, 
1615                             "Ignoring unknown metadata element: %s", type);
1616                 }
1617                 se->number_of_warnings_unknown_metadata++;
1618                 continue;
1619             }
1620            
1621             ser_md = &service->metadata[md_field_id];
1622
1623             // non-merged metadata
1624             rec_md = record_metadata_init(se->nmem, (const char *) value,
1625                                           ser_md->type, n->properties);
1626             if (!rec_md)
1627             {
1628                 session_log(se, YLOG_WARN, "bad metadata data '%s' "
1629                             "for element '%s'", value, type);
1630                 continue;
1631             }
1632             wheretoput = &record->metadata[md_field_id];
1633             while (*wheretoput)
1634                 wheretoput = &(*wheretoput)->next;
1635             *wheretoput = rec_md;
1636         }
1637     }
1638
1639     cluster = reclist_insert(se->reclist, service, record,
1640                              mergekey_norm, &se->total_merged);
1641     if (!cluster)
1642         return -1;
1643
1644     {
1645         const char *use_term_factor_str =
1646             session_setting_oneval(sdb, PZ_TERMLIST_TERM_FACTOR);
1647         if (use_term_factor_str && use_term_factor_str[0] == '1')
1648         {
1649             int maxrecs = client_get_maxrecs(cl);
1650             int hits = (int) client_get_hits(cl);
1651             term_factor = MAX(hits, maxrecs) /  MAX(1, maxrecs);
1652             assert(term_factor >= 1);
1653             yaz_log(YLOG_DEBUG, "Using term factor: %d (%d / %d)", term_factor, MAX(hits, maxrecs), MAX(1, maxrecs));
1654         }
1655     }
1656
1657     if (global_parameters.dump_records)
1658         session_log(se, YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
1659                     sdb->database->id, record_no);
1660
1661
1662     relevance_newrec(se->relevance, cluster);
1663     
1664     // now parsing XML record and adding data to cluster or record metadata
1665     for (n = root->children; n; n = n->next)
1666     {
1667         pp2_charset_token_t prt;
1668         if (type)
1669             xmlFree(type);
1670         if (value)
1671             xmlFree(value);
1672         type = value = 0;
1673         
1674         if (n->type != XML_ELEMENT_NODE)
1675             continue;
1676         if (!strcmp((const char *) n->name, "metadata"))
1677         {
1678             struct conf_metadata *ser_md = 0;
1679             struct conf_sortkey *ser_sk = 0;
1680             struct record_metadata **wheretoput = 0;
1681             struct record_metadata *rec_md = 0;
1682             int md_field_id = -1;
1683             int sk_field_id = -1;
1684             
1685             type = xmlGetProp(n, (xmlChar *) "type");
1686             value = xmlNodeListGetString(xdoc, n->children, 1);
1687             
1688             if (!type || !value || !*value)
1689                 continue;
1690             
1691             md_field_id 
1692                 = conf_service_metadata_field_id(service, (const char *) type);
1693             if (md_field_id < 0)
1694                 continue;
1695             
1696             ser_md = &service->metadata[md_field_id];
1697             
1698             if (ser_md->sortkey_offset >= 0)
1699             {
1700                 sk_field_id = ser_md->sortkey_offset;
1701                 ser_sk = &service->sortkeys[sk_field_id];
1702             }
1703
1704             // merged metadata
1705             rec_md = record_metadata_init(se->nmem, (const char *) value,
1706                                           ser_md->type, 0);
1707             if (!rec_md)
1708                 continue;
1709
1710             wheretoput = &cluster->metadata[md_field_id];
1711
1712             // and polulate with data:
1713             // assign cluster or record based on merge action
1714             if (ser_md->merge == Metadata_merge_unique)
1715             {
1716                 while (*wheretoput)
1717                 {
1718                     if (!strcmp((const char *) (*wheretoput)->data.text.disp, 
1719                                 rec_md->data.text.disp))
1720                         break;
1721                     wheretoput = &(*wheretoput)->next;
1722                 }
1723                 if (!*wheretoput)
1724                     *wheretoput = rec_md;
1725             }
1726             else if (ser_md->merge == Metadata_merge_longest)
1727             {
1728                 if (!*wheretoput 
1729                     || strlen(rec_md->data.text.disp) 
1730                     > strlen((*wheretoput)->data.text.disp))
1731                 {
1732                     *wheretoput = rec_md;
1733                     if (ser_sk)
1734                     {
1735                         const char *sort_str = 0;
1736                         int skip_article = 
1737                             ser_sk->type == Metadata_sortkey_skiparticle;
1738
1739                         if (!cluster->sortkeys[sk_field_id])
1740                             cluster->sortkeys[sk_field_id] = 
1741                                 nmem_malloc(se->nmem, 
1742                                             sizeof(union data_types));
1743                          
1744                         prt =
1745                             pp2_charset_token_create(service->charsets, "sort");
1746
1747                         pp2_charset_token_first(prt, rec_md->data.text.disp,
1748                                                 skip_article);
1749
1750                         pp2_charset_token_next(prt);
1751                          
1752                         sort_str = pp2_get_sort(prt);
1753                          
1754                         cluster->sortkeys[sk_field_id]->text.disp = 
1755                             rec_md->data.text.disp;
1756                         if (!sort_str)
1757                         {
1758                             sort_str = rec_md->data.text.disp;
1759                             session_log(se, YLOG_WARN, 
1760                                     "Could not make sortkey. Bug #1858");
1761                         }
1762                         cluster->sortkeys[sk_field_id]->text.sort = 
1763                             nmem_strdup(se->nmem, sort_str);
1764                         pp2_charset_token_destroy(prt);
1765                     }
1766                 }
1767             }
1768             else if (ser_md->merge == Metadata_merge_all)
1769             {
1770                 while (*wheretoput)
1771                     wheretoput = &(*wheretoput)->next;
1772                 *wheretoput = rec_md;
1773             }
1774             else if (ser_md->merge == Metadata_merge_range)
1775             {
1776                 if (!*wheretoput)
1777                 {
1778                     *wheretoput = rec_md;
1779                     if (ser_sk)
1780                         cluster->sortkeys[sk_field_id] 
1781                             = &rec_md->data;
1782                 }
1783                 else
1784                 {
1785                     int this_min = rec_md->data.number.min;
1786                     int this_max = rec_md->data.number.max;
1787                     if (this_min < (*wheretoput)->data.number.min)
1788                         (*wheretoput)->data.number.min = this_min;
1789                     if (this_max > (*wheretoput)->data.number.max)
1790                         (*wheretoput)->data.number.max = this_max;
1791                 }
1792             }
1793
1794
1795             // ranking of _all_ fields enabled ... 
1796             if (ser_md->rank)
1797                 relevance_countwords(se->relevance, cluster, 
1798                                      (char *) value, ser_md->rank,
1799                                      ser_md->name);
1800
1801             // construct facets ... unless the client already has reported them
1802             if (ser_md->termlist && !client_has_facet(cl, (char *) type))
1803             {
1804                 if (ser_md->type == Metadata_type_year)
1805                 {
1806                     char year[64];
1807                     sprintf(year, "%d", rec_md->data.number.max);
1808
1809                     add_facet(se, (char *) type, year, term_factor);
1810                     if (rec_md->data.number.max != rec_md->data.number.min)
1811                     {
1812                         sprintf(year, "%d", rec_md->data.number.min);
1813                         add_facet(se, (char *) type, year, term_factor);
1814                     }
1815                 }
1816                 else
1817                     add_facet(se, (char *) type, (char *) value, term_factor);
1818             }
1819
1820             // cleaning up
1821             xmlFree(type);
1822             xmlFree(value);
1823             type = value = 0;
1824         }
1825         else
1826         {
1827             if (se->number_of_warnings_unknown_elements == 0)
1828                 session_log(se, YLOG_WARN,
1829                         "Unexpected element in internal record: %s", n->name);
1830             se->number_of_warnings_unknown_elements++;
1831         }
1832     }
1833     if (type)
1834         xmlFree(type);
1835     if (value)
1836         xmlFree(value);
1837
1838     relevance_donerecord(se->relevance, cluster);
1839     se->total_records++;
1840
1841     return 0;
1842 }
1843
1844 void session_log(struct session *s, int level, const char *fmt, ...)
1845 {
1846     char buf[1024];
1847     va_list ap;
1848     va_start(ap, fmt);
1849
1850     yaz_vsnprintf(buf, sizeof(buf)-30, fmt, ap);
1851     yaz_log(level, "Session (%u): %s", s->session_id, buf);
1852
1853     va_end(ap);
1854 }
1855
1856 /*
1857  * Local variables:
1858  * c-basic-offset: 4
1859  * c-file-style: "Stroustrup"
1860  * indent-tabs-mode: nil
1861  * End:
1862  * vim: shiftwidth=4 tabstop=8 expandtab
1863  */
1864