Clients cached within session
[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;
534     se->clients = l;
535 }
536
537 static void session_remove_clients(struct session *se)
538 {
539     struct client_list *l;
540
541     session_enter(se);
542     l = se->clients;
543     se->clients = 0;
544     session_leave(se);
545
546     while (l)
547     {
548         struct client_list *l_next = l->next;
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_remove_clients(se);
559
560     session_enter(se);
561     l = se->clients_cached;
562     se->clients_cached = 0;
563     session_leave(se);
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; 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; 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 const char *get_strategy_plus_sort(struct client *l, const char *field)
611 {
612     struct session_database *sdb = client_get_database(l);
613     struct setting *s;
614
615     const char *strategy_plus_sort = 0;
616     
617     for (s = sdb->settings[PZ_SORTMAP]; s; s = s->next)
618     {
619         char *p = strchr(s->name + 3, ':');
620         if (!p)
621         {
622             yaz_log(YLOG_WARN, "Malformed sortmap name: %s", s->name);
623             continue;
624         }
625         p++;
626         if (!strcmp(p, field))
627         {
628             strategy_plus_sort = s->value;
629             break;
630         }
631     }
632     return strategy_plus_sort;
633 }
634
635 void session_sort(struct session *se, const char *field, int increasing)
636 {
637     struct session_sorted_results *sr;
638     struct client_list *l;
639
640     session_enter(se);
641
642     /* see if we already have sorted for this critieria */
643     for (sr = se->sorted_results; sr; sr = sr->next)
644     {
645         if (!strcmp(field, sr->field) && increasing == sr->increasing)
646             break;
647     }
648     if (sr)
649     {
650         yaz_log(YLOG_LOG, "search_sort: field=%s increasing=%d already fetched",
651                 field, increasing);
652         session_leave(se);
653         return;
654     }
655     yaz_log(YLOG_LOG, "search_sort: field=%s increasing=%d must fetch",
656             field, increasing);
657     sr = nmem_malloc(se->nmem, sizeof(*sr));
658     sr->field = nmem_strdup(se->nmem, field);
659     sr->increasing = increasing;
660     sr->next = se->sorted_results;
661     se->sorted_results = sr;
662     
663     for (l = se->clients; l; l = l->next)
664     {
665         struct client *cl = l->client;
666         const char *strategy_plus_sort = get_strategy_plus_sort(cl, field);
667         if (strategy_plus_sort)
668         {
669             struct timeval tval;
670             if (client_prep_connection(cl, se->service->z3950_operation_timeout,
671                                        se->service->z3950_session_timeout,
672                                        se->service->server->iochan_man,
673                                        &tval))
674                 client_start_search(cl, strategy_plus_sort, increasing);
675         }
676     }
677     session_leave(se);
678 }
679
680 enum pazpar2_error_code session_search(struct session *se,
681                                        const char *query,
682                                        const char *startrecs,
683                                        const char *maxrecs,
684                                        const char *filter,
685                                        const char *limit,
686                                        const char **addinfo,
687                                        const char *sort_field, int increasing)
688 {
689     int live_channels = 0;
690     int no_working = 0;
691     int no_failed = 0;
692     struct client_list *l;
693     struct timeval tval;
694     facet_limits_t facet_limits;
695
696     session_log(se, YLOG_DEBUG, "Search");
697
698     *addinfo = 0;
699
700     if (se->settings_modified)
701         session_remove_cached_clients(se);
702     else
703         session_remove_clients(se);
704     
705     session_enter(se);
706     reclist_destroy(se->reclist);
707     se->reclist = 0;
708     se->settings_modified = 0;
709     relevance_destroy(&se->relevance);
710     nmem_reset(se->nmem);
711     se->total_records = se->total_merged = 0;
712     se->num_termlists = 0;
713
714     /* reset list of sorted results and clear to relevance search */
715     se->sorted_results = nmem_malloc(se->nmem, sizeof(*se->sorted_results));
716     se->sorted_results->field = nmem_strdup(se->nmem, sort_field);
717     se->sorted_results->increasing = increasing;
718     se->sorted_results->next = 0;
719     
720     live_channels = select_targets(se, filter);
721     if (!live_channels)
722     {
723         session_leave(se);
724         return PAZPAR2_NO_TARGETS;
725     }
726     se->reclist = reclist_create(se->nmem);
727
728     yaz_gettimeofday(&tval);
729     
730     tval.tv_sec += 5;
731
732     facet_limits = facet_limits_create(limit);
733     if (!facet_limits)
734     {
735         *addinfo = "limit";
736         session_leave(se);
737         return PAZPAR2_MALFORMED_PARAMETER_VALUE;
738     }
739     for (l = se->clients; l; l = l->next)
740     {
741         int parse_ret;
742         struct client *cl = l->client;
743         const char *strategy_plus_sort = get_strategy_plus_sort(cl, sort_field);
744
745         if (prepare_map(se, client_get_database(cl)) < 0)
746             continue;
747
748         parse_ret = client_parse_query(cl, query, facet_limits, startrecs,
749             maxrecs);
750         if (parse_ret < 0)
751             no_failed++;
752         else if (parse_ret == 0)
753         {
754             yaz_log(YLOG_LOG, "client NEW %s", client_get_id(cl));
755             no_working++;
756             if (client_prep_connection(cl, se->service->z3950_operation_timeout,
757                                        se->service->z3950_session_timeout,
758                                        se->service->server->iochan_man,
759                                        &tval))
760                 client_start_search(cl, strategy_plus_sort, increasing);
761         }
762         else
763         {
764             yaz_log(YLOG_LOG, "client REUSE %s", client_get_id(cl));
765             no_working++;
766             if (client_prep_connection(cl, se->service->z3950_operation_timeout,
767                                        se->service->z3950_session_timeout,
768                                        se->service->server->iochan_man,
769                                        &tval))
770             {
771                 session_leave(se);
772                 client_reingest(cl);
773                 session_enter(se);
774             }
775         }
776     }
777     facet_limits_destroy(facet_limits);
778     session_leave(se);
779     if (no_working == 0)
780     {
781         if (no_failed > 0)
782         {
783             *addinfo = "query";
784             return PAZPAR2_MALFORMED_PARAMETER_VALUE;
785         }
786         else
787             return PAZPAR2_NO_TARGETS;
788     }
789     yaz_log(YLOG_LOG, "session_start_search done");
790     return PAZPAR2_NO_ERROR;
791 }
792
793 // Creates a new session_database object for a database
794 static void session_init_databases_fun(void *context, struct database *db)
795 {
796     struct session *se = (struct session *) context;
797     struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
798     int i;
799
800     new->database = db;
801     
802     new->map = 0;
803     assert(db->settings);
804     new->settings = nmem_malloc(se->session_nmem,
805                                 sizeof(struct settings *) * db->num_settings);
806     new->num_settings = db->num_settings;
807     for (i = 0; i < db->num_settings; i++)
808     {
809         struct setting *setting = db->settings[i];
810         new->settings[i] = setting;
811     }
812     new->next = se->databases;
813     se->databases = new;
814 }
815
816 // Doesn't free memory associated with sdb -- nmem takes care of that
817 static void session_database_destroy(struct session_database *sdb)
818 {
819     sdb->map = 0;
820 }
821
822 // Initialize session_database list -- this represents this session's view
823 // of the database list -- subject to modification by the settings ws command
824 void session_init_databases(struct session *se)
825 {
826     se->databases = 0;
827     predef_grep_databases(se, se->service, session_init_databases_fun);
828 }
829
830 // Probably session_init_databases_fun should be refactored instead of
831 // called here.
832 static struct session_database *load_session_database(struct session *se, 
833                                                       char *id)
834 {
835     struct database *db = new_database(id, se->session_nmem);
836
837     session_init_databases_fun((void*) se, db);
838
839     // New sdb is head of se->databases list
840     return se->databases;
841 }
842
843 // Find an existing session database. If not found, load it
844 static struct session_database *find_session_database(struct session *se, 
845                                                       char *id)
846 {
847     struct session_database *sdb;
848
849     for (sdb = se->databases; sdb; sdb = sdb->next)
850         if (!strcmp(sdb->database->id, id))
851             return sdb;
852     return load_session_database(se, id);
853 }
854
855 // Apply a session override to a database
856 void session_apply_setting(struct session *se, char *dbname, char *setting,
857                            char *value)
858 {
859     struct session_database *sdb = find_session_database(se, dbname);
860     struct conf_service *service = se->service;
861     struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
862     int offset = settings_create_offset(service, setting);
863
864     expand_settings_array(&sdb->settings, &sdb->num_settings, offset,
865                           se->session_nmem);
866     new->precedence = 0;
867     new->target = dbname;
868     new->name = setting;
869     new->value = value;
870     new->next = sdb->settings[offset];
871     sdb->settings[offset] = new;
872
873     se->settings_modified = 1;
874
875     // Force later recompute of settings-driven data structures
876     // (happens when a search starts and client connections are prepared)
877     switch (offset)
878     {
879     case PZ_XSLT:
880         if (sdb->map)
881         {
882             sdb->map = 0;
883         }
884         break;
885     }
886 }
887
888 void session_destroy(struct session *se)
889 {
890     struct session_database *sdb;
891     session_log(se, YLOG_DEBUG, "Destroying");
892     session_use(-1);
893     session_remove_cached_clients(se);
894
895     for (sdb = se->databases; sdb; sdb = sdb->next)
896         session_database_destroy(sdb);
897     normalize_cache_destroy(se->normalize_cache);
898     relevance_destroy(&se->relevance);
899     reclist_destroy(se->reclist);
900     nmem_destroy(se->nmem);
901     service_destroy(se->service);
902     yaz_mutex_destroy(&se->session_mutex);
903 }
904
905 /* Depreciated: use session_destroy */
906 void destroy_session(struct session *se)
907 {
908     session_destroy(se);
909 }
910
911 size_t session_get_memory_status(struct session *session) {
912     size_t session_nmem;
913     if (session == 0)
914         return 0;
915     session_enter(session);
916     session_nmem = nmem_total(session->nmem);
917     session_leave(session);
918     return session_nmem;
919 }
920
921
922 struct session *new_session(NMEM nmem, struct conf_service *service,
923                             unsigned session_id)
924 {
925     int i;
926     struct session *session = nmem_malloc(nmem, sizeof(*session));
927
928     char tmp_str[50];
929
930     sprintf(tmp_str, "session#%u", session_id);
931
932     session->session_id = session_id;
933     session_log(session, YLOG_DEBUG, "New");
934     session->service = service;
935     session->relevance = 0;
936     session->total_records = 0;
937     session->number_of_warnings_unknown_elements = 0;
938     session->number_of_warnings_unknown_metadata = 0;
939     session->num_termlists = 0;
940     session->reclist = 0;
941     session->clients = 0;
942     session->clients_cached = 0;
943     session->settings_modified = 0;
944     session->session_nmem = nmem;
945     session->nmem = nmem_create();
946     session->databases = 0;
947     for (i = 0; i <= SESSION_WATCH_MAX; i++)
948     {
949         session->watchlist[i].data = 0;
950         session->watchlist[i].fun = 0;
951     }
952     session->normalize_cache = normalize_cache_create();
953     session->session_mutex = 0;
954     pazpar2_mutex_create(&session->session_mutex, tmp_str);
955     session_use(1);
956     return session;
957 }
958
959 const char * client_get_suggestions_xml(struct client *cl, WRBUF wrbuf);
960
961 static struct hitsbytarget *hitsbytarget_nb(struct session *se,
962                                             int *count, NMEM nmem)
963 {
964     struct hitsbytarget *res = 0;
965     struct client_list *l;
966     size_t sz = 0;
967
968     for (l = se->clients; l; l = l->next)
969         sz++;
970
971     res = nmem_malloc(nmem, sizeof(*res) * sz);
972     *count = 0;
973     for (l = se->clients; l; l = l->next)
974     {
975         struct client *cl = l->client;
976         WRBUF w = wrbuf_alloc();
977         const char *name = session_setting_oneval(client_get_database(cl),
978                                                   PZ_NAME);
979
980         res[*count].id = client_get_id(cl);
981         res[*count].name = *name ? name : "Unknown";
982         res[*count].hits = client_get_hits(cl);
983         res[*count].records = client_get_num_records(cl);
984         res[*count].diagnostic = client_get_diagnostic(cl);
985         res[*count].state = client_get_state_str(cl);
986         res[*count].connected  = client_get_connection(cl) ? 1 : 0;
987         session_settings_dump(se, client_get_database(cl), w);
988         res[*count].settings_xml = nmem_strdup(nmem, wrbuf_cstr(w));
989         wrbuf_rewind(w);
990         wrbuf_puts(w, "");
991         res[*count].suggestions_xml = nmem_strdup(nmem, client_get_suggestions_xml(cl, w));
992         wrbuf_destroy(w);
993         (*count)++;
994     }
995     return res;
996 }
997
998 struct hitsbytarget *get_hitsbytarget(struct session *se, int *count, NMEM nmem)
999 {
1000     struct hitsbytarget *p;
1001     session_enter(se);
1002     p = hitsbytarget_nb(se, count, nmem);
1003     session_leave(se);
1004     return p;
1005 }
1006     
1007 struct termlist_score **get_termlist_score(struct session *se,
1008                                            const char *name, int *num)
1009 {
1010     int i;
1011     struct termlist_score **tl = 0;
1012
1013     session_enter(se);
1014     for (i = 0; i < se->num_termlists; i++)
1015         if (!strcmp((const char *) se->termlists[i].name, name))
1016         {
1017             tl = termlist_highscore(se->termlists[i].termlist, num);
1018             break;
1019         }
1020     session_leave(se);
1021     return tl;
1022 }
1023
1024 // Compares two hitsbytarget nodes by hitcount
1025 static int cmp_ht(const void *p1, const void *p2)
1026 {
1027     const struct hitsbytarget *h1 = p1;
1028     const struct hitsbytarget *h2 = p2;
1029     return h2->hits - h1->hits;
1030 }
1031
1032 static int targets_termlist_nb(WRBUF wrbuf, struct session *se, int num,
1033                                NMEM nmem)
1034 {
1035     struct hitsbytarget *ht;
1036     int count, i;
1037
1038     ht = hitsbytarget_nb(se, &count, nmem);
1039     qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht);
1040     for (i = 0; i < count && i < num && ht[i].hits > 0; i++)
1041     {
1042
1043         // do only print terms which have display names
1044     
1045         wrbuf_puts(wrbuf, "<term>\n");
1046
1047         wrbuf_puts(wrbuf, "<id>");
1048         wrbuf_xmlputs(wrbuf, ht[i].id);
1049         wrbuf_puts(wrbuf, "</id>\n");
1050         
1051         wrbuf_puts(wrbuf, "<name>");
1052         if (!ht[i].name || !ht[i].name[0])
1053             wrbuf_xmlputs(wrbuf, "NO TARGET NAME");
1054         else
1055             wrbuf_xmlputs(wrbuf, ht[i].name);
1056         wrbuf_puts(wrbuf, "</name>\n");
1057         
1058         wrbuf_printf(wrbuf, "<frequency>" ODR_INT_PRINTF "</frequency>\n",
1059                      ht[i].hits);
1060         
1061         wrbuf_puts(wrbuf, "<state>");
1062         wrbuf_xmlputs(wrbuf, ht[i].state);
1063         wrbuf_puts(wrbuf, "</state>\n");
1064         
1065         wrbuf_printf(wrbuf, "<diagnostic>%d</diagnostic>\n", 
1066                      ht[i].diagnostic);
1067         wrbuf_puts(wrbuf, "</term>\n");
1068     }
1069     return count;
1070 }
1071
1072 void perform_termlist(struct http_channel *c, struct session *se,
1073                       const char *name, int num)
1074 {
1075     int i, j;
1076     NMEM nmem_tmp = nmem_create();
1077     char **names;
1078     int num_names = 0;
1079
1080     if (name)
1081         nmem_strsplit(nmem_tmp, ",", name, &names, &num_names);
1082
1083     session_enter(se);
1084
1085     for (j = 0; j < num_names; j++)
1086     {
1087         const char *tname;
1088         
1089         wrbuf_puts(c->wrbuf, "<list name=\"");
1090         wrbuf_xmlputs(c->wrbuf, names[j]);
1091         wrbuf_puts(c->wrbuf, "\">\n");
1092
1093         for (i = 0; i < se->num_termlists; i++)
1094         {
1095             tname = se->termlists[i].name;
1096             if (num_names > 0 && !strcmp(names[j], tname))
1097             {
1098                 struct termlist_score **p = 0;
1099                 int len;
1100                 p = termlist_highscore(se->termlists[i].termlist, &len);
1101                 if (p)
1102                 {
1103                     int i;
1104                     for (i = 0; i < len && i < num; i++)
1105                     {
1106                         // prevent sending empty term elements
1107                         if (!p[i]->display_term || !p[i]->display_term[0])
1108                             continue;
1109                         
1110                         wrbuf_puts(c->wrbuf, "<term>");
1111                         wrbuf_puts(c->wrbuf, "<name>");
1112                         wrbuf_xmlputs(c->wrbuf, p[i]->display_term);
1113                         wrbuf_puts(c->wrbuf, "</name>");
1114                         
1115                         wrbuf_printf(c->wrbuf, 
1116                                      "<frequency>%d</frequency>", 
1117                                      p[i]->frequency);
1118                         wrbuf_puts(c->wrbuf, "</term>\n");
1119                     }
1120                 }
1121             }
1122         }
1123         tname = "xtargets";
1124         if (num_names > 0 && !strcmp(names[j], tname))
1125         {
1126             targets_termlist_nb(c->wrbuf, se, num, c->nmem);
1127         }
1128         wrbuf_puts(c->wrbuf, "</list>\n");
1129     }
1130     session_leave(se);
1131     nmem_destroy(nmem_tmp);
1132 }
1133
1134 #ifdef MISSING_HEADERS
1135 void report_nmem_stats(void)
1136 {
1137     size_t in_use, is_free;
1138
1139     nmem_get_memory_in_use(&in_use);
1140     nmem_get_memory_free(&is_free);
1141
1142     yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld", 
1143             (long) in_use, (long) is_free);
1144 }
1145 #endif
1146
1147 struct record_cluster *show_single_start(struct session *se, const char *id,
1148                                          struct record_cluster **prev_r,
1149                                          struct record_cluster **next_r)
1150 {
1151     struct record_cluster *r = 0;
1152
1153     session_enter(se);
1154     *prev_r = 0;
1155     *next_r = 0;
1156     if (se->reclist)
1157     {
1158         reclist_enter(se->reclist);
1159         while ((r = reclist_read_record(se->reclist)))
1160         {
1161             if (!strcmp(r->recid, id))
1162             {
1163                 *next_r = reclist_read_record(se->reclist);
1164                 break;
1165             }
1166             *prev_r = r;
1167         }
1168         reclist_leave(se->reclist);
1169     }
1170     if (!r)
1171         session_leave(se);
1172     return r;
1173 }
1174
1175 void show_single_stop(struct session *se, struct record_cluster *rec)
1176 {
1177     session_leave(se);
1178 }
1179
1180 struct record_cluster **show_range_start(struct session *se,
1181                                          struct reclist_sortparms *sp, 
1182                                          int start, int *num, int *total, Odr_int *sumhits)
1183 {
1184     struct record_cluster **recs;
1185     struct reclist_sortparms *spp;
1186     int i;
1187 #if USE_TIMING    
1188     yaz_timing_t t = yaz_timing_create();
1189 #endif
1190     session_enter(se);
1191     recs = nmem_malloc(se->nmem, *num * sizeof(struct record_cluster *));
1192     if (!se->relevance)
1193     {
1194         *num = 0;
1195         *total = 0;
1196         *sumhits = 0;
1197         recs = 0;
1198     }
1199     else
1200     {
1201         struct client_list *l;
1202         
1203         for (spp = sp; spp; spp = spp->next)
1204             if (spp->type == Metadata_sortkey_relevance)
1205             {
1206                 relevance_prepare_read(se->relevance, se->reclist);
1207                 break;
1208             }
1209         reclist_sort(se->reclist, sp);
1210         
1211         reclist_enter(se->reclist);
1212         *total = reclist_get_num_records(se->reclist);
1213
1214         *sumhits = 0;
1215         for (l = se->clients; l; l = l->next)
1216             *sumhits += client_get_hits(l->client);
1217         
1218         for (i = 0; i < start; i++)
1219             if (!reclist_read_record(se->reclist))
1220             {
1221                 *num = 0;
1222                 recs = 0;
1223                 break;
1224             }
1225         
1226         for (i = 0; i < *num; i++)
1227         {
1228             struct record_cluster *r = reclist_read_record(se->reclist);
1229             if (!r)
1230             {
1231                 *num = i;
1232                 break;
1233             }
1234             recs[i] = r;
1235         }
1236         reclist_leave(se->reclist);
1237     }
1238 #if USE_TIMING
1239     yaz_timing_stop(t);
1240     yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f", 
1241             yaz_timing_get_real(t), yaz_timing_get_user(t),
1242             yaz_timing_get_sys(t));
1243     yaz_timing_destroy(&t);
1244 #endif
1245     return recs;
1246 }
1247
1248 void show_range_stop(struct session *se, struct record_cluster **recs)
1249 {
1250     session_leave(se);
1251 }
1252
1253 void statistics(struct session *se, struct statistics *stat)
1254 {
1255     struct client_list *l;
1256     int count = 0;
1257
1258     memset(stat, 0, sizeof(*stat));
1259     stat->num_hits = 0;
1260     for (l = se->clients; l; l = l->next)
1261     {
1262         struct client *cl = l->client;
1263         if (!client_get_connection(cl))
1264             stat->num_no_connection++;
1265         stat->num_hits += client_get_hits(cl);
1266         switch (client_get_state(cl))
1267         {
1268         case Client_Connecting: stat->num_connecting++; break;
1269         case Client_Working: stat->num_working++; break;
1270         case Client_Idle: stat->num_idle++; break;
1271         case Client_Failed: stat->num_failed++; break;
1272         case Client_Error: stat->num_error++; break;
1273         default: break;
1274         }
1275         count++;
1276     }
1277     stat->num_records = se->total_records;
1278
1279     stat->num_clients = count;
1280 }
1281
1282 static struct record_metadata *record_metadata_init(
1283     NMEM nmem, const char *value, enum conf_metadata_type type,
1284     struct _xmlAttr *attr)
1285 {
1286     struct record_metadata *rec_md = record_metadata_create(nmem);
1287     struct record_metadata_attr **attrp = &rec_md->attributes;
1288     
1289     for (; attr; attr = attr->next)
1290     {
1291         if (attr->children && attr->children->content)
1292         {
1293             if (strcmp((const char *) attr->name, "type"))
1294             {  /* skip the "type" attribute.. Its value is already part of
1295                   the element in output (md-%s) and so repeating it here
1296                   is redundant */
1297                 *attrp = nmem_malloc(nmem, sizeof(**attrp));
1298                 (*attrp)->name =
1299                     nmem_strdup(nmem, (const char *) attr->name);
1300                 (*attrp)->value =
1301                     nmem_strdup(nmem, (const char *) attr->children->content);
1302                 attrp = &(*attrp)->next;
1303             }
1304         }
1305     }
1306     *attrp = 0;
1307
1308     if (type == Metadata_type_generic)
1309     {
1310         char *p = nmem_strdup(nmem, value);
1311
1312         p = normalize7bit_generic(p, " ,/.:([");
1313         
1314         rec_md->data.text.disp = p;
1315         rec_md->data.text.sort = 0;
1316     }
1317     else if (type == Metadata_type_year || type == Metadata_type_date)
1318     {
1319         int first, last;
1320         int longdate = 0;
1321
1322         if (type == Metadata_type_date)
1323             longdate = 1;
1324         if (extract7bit_dates((char *) value, &first, &last, longdate) < 0)
1325             return 0;
1326
1327         rec_md->data.number.min = first;
1328         rec_md->data.number.max = last;
1329     }
1330     else
1331         return 0;
1332     return rec_md;
1333 }
1334
1335 static int get_mergekey_from_doc(xmlDoc *doc, xmlNode *root, const char *name,
1336                                  struct conf_service *service, WRBUF norm_wr)
1337 {
1338     xmlNode *n;
1339     int no_found = 0;
1340     for (n = root->children; n; n = n->next)
1341     {
1342         if (n->type != XML_ELEMENT_NODE)
1343             continue;
1344         if (!strcmp((const char *) n->name, "metadata"))
1345         {
1346             xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1347             if (type == NULL) {
1348                 yaz_log(YLOG_FATAL, "Missing type attribute on metadata element. Skipping!");
1349             }
1350             else if (!strcmp(name, (const char *) type))
1351             {
1352                 xmlChar *value = xmlNodeListGetString(doc, n->children, 1);
1353                 if (value)
1354                 {
1355                     const char *norm_str;
1356                     pp2_charset_token_t prt =
1357                         pp2_charset_token_create(service->charsets, "mergekey");
1358                     
1359                     pp2_charset_token_first(prt, (const char *) value, 0);
1360                     if (wrbuf_len(norm_wr) > 0)
1361                         wrbuf_puts(norm_wr, " ");
1362                     wrbuf_puts(norm_wr, name);
1363                     while ((norm_str =
1364                             pp2_charset_token_next(prt)))
1365                     {
1366                         if (*norm_str)
1367                         {
1368                             wrbuf_puts(norm_wr, " ");
1369                             wrbuf_puts(norm_wr, norm_str);
1370                         }
1371                     }
1372                     xmlFree(value);
1373                     pp2_charset_token_destroy(prt);
1374                     no_found++;
1375                 }
1376             }
1377             xmlFree(type);
1378         }
1379     }
1380     return no_found;
1381 }
1382
1383 static const char *get_mergekey(xmlDoc *doc, struct client *cl, int record_no,
1384                                 struct conf_service *service, NMEM nmem)
1385 {
1386     char *mergekey_norm = 0;
1387     xmlNode *root = xmlDocGetRootElement(doc);
1388     WRBUF norm_wr = wrbuf_alloc();
1389
1390     /* consider mergekey from XSL first */
1391     xmlChar *mergekey = xmlGetProp(root, (xmlChar *) "mergekey");
1392     if (mergekey)
1393     {
1394         const char *norm_str;
1395         pp2_charset_token_t prt =
1396             pp2_charset_token_create(service->charsets, "mergekey");
1397
1398         pp2_charset_token_first(prt, (const char *) mergekey, 0);
1399         while ((norm_str = pp2_charset_token_next(prt)))
1400         {
1401             if (*norm_str)
1402             {
1403                 if (wrbuf_len(norm_wr))
1404                     wrbuf_puts(norm_wr, " ");
1405                 wrbuf_puts(norm_wr, norm_str);
1406             }
1407         }
1408         pp2_charset_token_destroy(prt);
1409         xmlFree(mergekey);
1410     }
1411     else
1412     {
1413         /* no mergekey defined in XSL. Look for mergekey metadata instead */
1414         int field_id;
1415         for (field_id = 0; field_id < service->num_metadata; field_id++)
1416         {
1417             struct conf_metadata *ser_md = &service->metadata[field_id];
1418             if (ser_md->mergekey != Metadata_mergekey_no)
1419             {
1420                 int r = get_mergekey_from_doc(doc, root, ser_md->name,
1421                                               service, norm_wr);
1422                 if (r == 0 && ser_md->mergekey == Metadata_mergekey_required)
1423                 {
1424                     /* no mergekey on this one and it is required.. 
1425                        Generate unique key instead */
1426                     wrbuf_rewind(norm_wr);
1427                     break;
1428                 }
1429             }
1430         }
1431     }
1432
1433     /* generate unique key if none is not generated already or is empty */
1434     if (wrbuf_len(norm_wr) == 0)
1435     {
1436         wrbuf_printf(norm_wr, "position: %s-%d",
1437                      client_get_id(cl), record_no);
1438     }
1439     else
1440     {
1441         const char *lead = "content: ";
1442         wrbuf_insert(norm_wr, 0, lead, strlen(lead));
1443     }
1444     if (wrbuf_len(norm_wr) > 0)
1445         mergekey_norm = nmem_strdup(nmem, wrbuf_cstr(norm_wr));
1446     wrbuf_destroy(norm_wr);
1447     return mergekey_norm;
1448 }
1449
1450 /** \brief see if metadata for pz:recordfilter exists 
1451     \param root xml root element of normalized record
1452     \param sdb session database for client
1453     \retval 0 if there is no metadata for pz:recordfilter
1454     \retval 1 if there is metadata for pz:recordfilter
1455
1456     If there is no pz:recordfilter defined, this function returns 1
1457     as well.
1458 */
1459     
1460 static int check_record_filter(xmlNode *root, struct session_database *sdb)
1461 {
1462     int match = 0;
1463     xmlNode *n;
1464     const char *s;
1465     s = session_setting_oneval(sdb, PZ_RECORDFILTER);
1466
1467     if (!s || !*s)
1468         return 1;
1469
1470     for (n = root->children; n; n = n->next)
1471     {
1472         if (n->type != XML_ELEMENT_NODE)
1473             continue;
1474         if (!strcmp((const char *) n->name, "metadata"))
1475         {
1476             xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1477             if (type)
1478             {
1479                 size_t len;
1480                 int substring;
1481                 const char *eq;
1482
1483                 if ((eq = strchr(s, '=')))
1484                     substring = 0;
1485                 else if ((eq = strchr(s, '~')))
1486                     substring = 1;
1487                 if (eq)
1488                     len = eq - s;
1489                 else
1490                     len = strlen(s);
1491                 if (len == strlen((const char *)type) &&
1492                     !memcmp((const char *) type, s, len))
1493                 {
1494                     xmlChar *value = xmlNodeGetContent(n);
1495                     if (value && *value)
1496                     {
1497                         if (!eq ||
1498                             (substring && strstr((const char *) value, eq+1)) ||
1499                             (!substring && !strcmp((const char *) value, eq + 1)))
1500                             match = 1;
1501                     }
1502                     xmlFree(value);
1503                 }
1504                 xmlFree(type);
1505             }
1506         }
1507     }
1508     return match;
1509 }
1510
1511
1512 static int ingest_to_cluster(struct client *cl,
1513                              xmlDoc *xdoc,
1514                              xmlNode *root,
1515                              int record_no,
1516                              const char *mergekey_norm);
1517
1518 /** \brief ingest XML record
1519     \param cl client holds the result set for record
1520     \param rec record buffer (0 terminated)
1521     \param record_no record position (1, 2, ..)
1522     \param nmem working NMEM
1523     \retval 0 OK
1524     \retval -1 failure
1525     \retval -2 Filtered
1526 */
1527 int ingest_record(struct client *cl, const char *rec,
1528                   int record_no, NMEM nmem)
1529 {
1530     struct session *se = client_get_session(cl);
1531     int ret = 0;
1532     struct session_database *sdb = client_get_database(cl);
1533     struct conf_service *service = se->service;
1534     xmlDoc *xdoc = normalize_record(se, sdb, service, rec, nmem);
1535     xmlNode *root;
1536     const char *mergekey_norm;
1537     
1538     if (!xdoc)
1539         return -1;
1540     
1541     root = xmlDocGetRootElement(xdoc);
1542     
1543     if (!check_record_filter(root, sdb))
1544     {
1545         session_log(se, YLOG_LOG, "Filtered out record no %d from %s",
1546                     record_no, sdb->database->id);
1547         xmlFreeDoc(xdoc);
1548         return -2;
1549     }
1550     
1551     mergekey_norm = get_mergekey(xdoc, cl, record_no, service, nmem);
1552     if (!mergekey_norm)
1553     {
1554         session_log(se, YLOG_WARN, "Got no mergekey");
1555         xmlFreeDoc(xdoc);
1556         return -1;
1557     }
1558     session_enter(se);
1559     if (client_get_session(cl) == se)
1560         ingest_to_cluster(cl, xdoc, root, record_no, mergekey_norm);
1561     session_leave(se);
1562     
1563     xmlFreeDoc(xdoc);
1564     return ret;
1565 }
1566
1567 static int ingest_to_cluster(struct client *cl,
1568                              xmlDoc *xdoc,
1569                              xmlNode *root,
1570                              int record_no,
1571                              const char *mergekey_norm)
1572 {
1573     xmlNode *n;
1574     xmlChar *type = 0;
1575     xmlChar *value = 0;
1576     struct session *se = client_get_session(cl);
1577     struct conf_service *service = se->service;
1578     int term_factor = 1;
1579     struct record_cluster *cluster;
1580     struct session_database *sdb = client_get_database(cl);
1581     struct record *record = record_create(se->nmem, 
1582                                           service->num_metadata,
1583                                           service->num_sortkeys, cl,
1584                                           record_no);
1585
1586     for (n = root->children; n; n = n->next)
1587     {
1588         if (type)
1589             xmlFree(type);
1590         if (value)
1591             xmlFree(value);
1592         type = value = 0;
1593         
1594         if (n->type != XML_ELEMENT_NODE)
1595             continue;
1596         if (!strcmp((const char *) n->name, "metadata"))
1597         {
1598             struct conf_metadata *ser_md = 0;
1599             struct record_metadata **wheretoput = 0;
1600             struct record_metadata *rec_md = 0;
1601             int md_field_id = -1;
1602             
1603             type = xmlGetProp(n, (xmlChar *) "type");
1604             value = xmlNodeListGetString(xdoc, n->children, 1);
1605             
1606             if (!type || !value || !*value)
1607                 continue;
1608             
1609             md_field_id 
1610                 = conf_service_metadata_field_id(service, (const char *) type);
1611             if (md_field_id < 0)
1612             {
1613                 if (se->number_of_warnings_unknown_metadata == 0)
1614                 {
1615                     session_log(se, YLOG_WARN, 
1616                             "Ignoring unknown metadata element: %s", type);
1617                 }
1618                 se->number_of_warnings_unknown_metadata++;
1619                 continue;
1620             }
1621            
1622             ser_md = &service->metadata[md_field_id];
1623
1624             // non-merged metadata
1625             rec_md = record_metadata_init(se->nmem, (const char *) value,
1626                                           ser_md->type, n->properties);
1627             if (!rec_md)
1628             {
1629                 session_log(se, YLOG_WARN, "bad metadata data '%s' "
1630                             "for element '%s'", value, type);
1631                 continue;
1632             }
1633             wheretoput = &record->metadata[md_field_id];
1634             while (*wheretoput)
1635                 wheretoput = &(*wheretoput)->next;
1636             *wheretoput = rec_md;
1637         }
1638     }
1639
1640     cluster = reclist_insert(se->reclist, service, record,
1641                              mergekey_norm, &se->total_merged);
1642     if (!cluster)
1643         return -1;
1644
1645     {
1646         const char *use_term_factor_str =
1647             session_setting_oneval(sdb, PZ_TERMLIST_TERM_FACTOR);
1648         if (use_term_factor_str && use_term_factor_str[0] == '1')
1649         {
1650             int maxrecs = client_get_maxrecs(cl);
1651             int hits = (int) client_get_hits(cl);
1652             term_factor = MAX(hits, maxrecs) /  MAX(1, maxrecs);
1653             assert(term_factor >= 1);
1654             yaz_log(YLOG_DEBUG, "Using term factor: %d (%d / %d)", term_factor, MAX(hits, maxrecs), MAX(1, maxrecs));
1655         }
1656     }
1657
1658     if (global_parameters.dump_records)
1659         session_log(se, YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
1660                     sdb->database->id, record_no);
1661
1662
1663     relevance_newrec(se->relevance, cluster);
1664     
1665     // now parsing XML record and adding data to cluster or record metadata
1666     for (n = root->children; n; n = n->next)
1667     {
1668         pp2_charset_token_t prt;
1669         if (type)
1670             xmlFree(type);
1671         if (value)
1672             xmlFree(value);
1673         type = value = 0;
1674         
1675         if (n->type != XML_ELEMENT_NODE)
1676             continue;
1677         if (!strcmp((const char *) n->name, "metadata"))
1678         {
1679             struct conf_metadata *ser_md = 0;
1680             struct conf_sortkey *ser_sk = 0;
1681             struct record_metadata **wheretoput = 0;
1682             struct record_metadata *rec_md = 0;
1683             int md_field_id = -1;
1684             int sk_field_id = -1;
1685             
1686             type = xmlGetProp(n, (xmlChar *) "type");
1687             value = xmlNodeListGetString(xdoc, n->children, 1);
1688             
1689             if (!type || !value || !*value)
1690                 continue;
1691             
1692             md_field_id 
1693                 = conf_service_metadata_field_id(service, (const char *) type);
1694             if (md_field_id < 0)
1695                 continue;
1696             
1697             ser_md = &service->metadata[md_field_id];
1698             
1699             if (ser_md->sortkey_offset >= 0)
1700             {
1701                 sk_field_id = ser_md->sortkey_offset;
1702                 ser_sk = &service->sortkeys[sk_field_id];
1703             }
1704
1705             // merged metadata
1706             rec_md = record_metadata_init(se->nmem, (const char *) value,
1707                                           ser_md->type, 0);
1708             if (!rec_md)
1709                 continue;
1710
1711             wheretoput = &cluster->metadata[md_field_id];
1712
1713             // and polulate with data:
1714             // assign cluster or record based on merge action
1715             if (ser_md->merge == Metadata_merge_unique)
1716             {
1717                 while (*wheretoput)
1718                 {
1719                     if (!strcmp((const char *) (*wheretoput)->data.text.disp, 
1720                                 rec_md->data.text.disp))
1721                         break;
1722                     wheretoput = &(*wheretoput)->next;
1723                 }
1724                 if (!*wheretoput)
1725                     *wheretoput = rec_md;
1726             }
1727             else if (ser_md->merge == Metadata_merge_longest)
1728             {
1729                 if (!*wheretoput 
1730                     || strlen(rec_md->data.text.disp) 
1731                     > strlen((*wheretoput)->data.text.disp))
1732                 {
1733                     *wheretoput = rec_md;
1734                     if (ser_sk)
1735                     {
1736                         const char *sort_str = 0;
1737                         int skip_article = 
1738                             ser_sk->type == Metadata_sortkey_skiparticle;
1739
1740                         if (!cluster->sortkeys[sk_field_id])
1741                             cluster->sortkeys[sk_field_id] = 
1742                                 nmem_malloc(se->nmem, 
1743                                             sizeof(union data_types));
1744                          
1745                         prt =
1746                             pp2_charset_token_create(service->charsets, "sort");
1747
1748                         pp2_charset_token_first(prt, rec_md->data.text.disp,
1749                                                 skip_article);
1750
1751                         pp2_charset_token_next(prt);
1752                          
1753                         sort_str = pp2_get_sort(prt);
1754                          
1755                         cluster->sortkeys[sk_field_id]->text.disp = 
1756                             rec_md->data.text.disp;
1757                         if (!sort_str)
1758                         {
1759                             sort_str = rec_md->data.text.disp;
1760                             session_log(se, YLOG_WARN, 
1761                                     "Could not make sortkey. Bug #1858");
1762                         }
1763                         cluster->sortkeys[sk_field_id]->text.sort = 
1764                             nmem_strdup(se->nmem, sort_str);
1765                         pp2_charset_token_destroy(prt);
1766                     }
1767                 }
1768             }
1769             else if (ser_md->merge == Metadata_merge_all)
1770             {
1771                 while (*wheretoput)
1772                     wheretoput = &(*wheretoput)->next;
1773                 *wheretoput = rec_md;
1774             }
1775             else if (ser_md->merge == Metadata_merge_range)
1776             {
1777                 if (!*wheretoput)
1778                 {
1779                     *wheretoput = rec_md;
1780                     if (ser_sk)
1781                         cluster->sortkeys[sk_field_id] 
1782                             = &rec_md->data;
1783                 }
1784                 else
1785                 {
1786                     int this_min = rec_md->data.number.min;
1787                     int this_max = rec_md->data.number.max;
1788                     if (this_min < (*wheretoput)->data.number.min)
1789                         (*wheretoput)->data.number.min = this_min;
1790                     if (this_max > (*wheretoput)->data.number.max)
1791                         (*wheretoput)->data.number.max = this_max;
1792                 }
1793             }
1794
1795
1796             // ranking of _all_ fields enabled ... 
1797             if (ser_md->rank)
1798                 relevance_countwords(se->relevance, cluster, 
1799                                      (char *) value, ser_md->rank,
1800                                      ser_md->name);
1801
1802             // construct facets ... unless the client already has reported them
1803             if (ser_md->termlist && !client_has_facet(cl, (char *) type))
1804             {
1805                 if (ser_md->type == Metadata_type_year)
1806                 {
1807                     char year[64];
1808                     sprintf(year, "%d", rec_md->data.number.max);
1809
1810                     add_facet(se, (char *) type, year, term_factor);
1811                     if (rec_md->data.number.max != rec_md->data.number.min)
1812                     {
1813                         sprintf(year, "%d", rec_md->data.number.min);
1814                         add_facet(se, (char *) type, year, term_factor);
1815                     }
1816                 }
1817                 else
1818                     add_facet(se, (char *) type, (char *) value, term_factor);
1819             }
1820
1821             // cleaning up
1822             xmlFree(type);
1823             xmlFree(value);
1824             type = value = 0;
1825         }
1826         else
1827         {
1828             if (se->number_of_warnings_unknown_elements == 0)
1829                 session_log(se, YLOG_WARN,
1830                         "Unexpected element in internal record: %s", n->name);
1831             se->number_of_warnings_unknown_elements++;
1832         }
1833     }
1834     if (type)
1835         xmlFree(type);
1836     if (value)
1837         xmlFree(value);
1838
1839     relevance_donerecord(se->relevance, cluster);
1840     se->total_records++;
1841
1842     return 0;
1843 }
1844
1845 void session_log(struct session *s, int level, const char *fmt, ...)
1846 {
1847     char buf[1024];
1848     va_list ap;
1849     va_start(ap, fmt);
1850
1851     yaz_vsnprintf(buf, sizeof(buf)-30, fmt, ap);
1852     yaz_log(level, "Session (%u): %s", s->session_id, buf);
1853
1854     va_end(ap);
1855 }
1856
1857 /*
1858  * Local variables:
1859  * c-basic-offset: 4
1860  * c-file-style: "Stroustrup"
1861  * indent-tabs-mode: nil
1862  * End:
1863  * vim: shiftwidth=4 tabstop=8 expandtab
1864  */
1865