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