1 ;;; registry.el --- Track and remember data items by various fields
3 ;; Copyright (C) 2011 Free Software Foundation, Inc.
5 ;; Author: Teodor Zlatanov <tzz@lifelogs.com>
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;; This library provides a general-purpose EIEIO-based registry
26 ;; database with persistence, initialized with these fields:
28 ;; version: a float, 0.1 currently (don't change it)
30 ;; max-hard: an integer, default 5000000
32 ;; max-soft: an integer, default 50000
34 ;; precious: a list of symbols
36 ;; tracked: a list of symbols
38 ;; tracker: a hashtable tuned for 100 symbols to track (you should
39 ;; only access this with the :lookup2-function and the
40 ;; :lookup2+-function)
42 ;; data: a hashtable with default size 10K and resize threshold 2.0
43 ;; (this reflects the expected usage so override it if you know better)
45 ;; ...plus methods to do all the work: `registry-search',
46 ;; `registry-lookup', `registry-lookup-secondary',
47 ;; `registry-lookup-secondary-value', `registry-insert',
48 ;; `registry-delete', `registry-prune', `registry-size' which see
50 ;; and with the following properties:
52 ;; Every piece of data has a unique ID and some general-purpose fields
53 ;; (F1=D1, F2=D2, F3=(a b c)...) expressed as an alist, e.g.
55 ;; ((F1 D1) (F2 D2) (F3 a b c))
57 ;; Note that whether a field has one or many pieces of data, the data
58 ;; is always a list of values.
60 ;; The user decides which fields are "precious", F2 for example. At
61 ;; PRUNE TIME (when the :prune-function is called), the registry will
62 ;; trim any entries without the F2 field until the size is :max-soft
63 ;; or less. No entries with the F2 field will be removed at PRUNE
66 ;; When an entry is inserted, the registry will reject new entries
67 ;; if they bring it over the max-hard limit, even if they have the F2
70 ;; The user decides which fields are "tracked", F1 for example. Any
71 ;; new entry is then indexed by all the tracked fields so it can be
72 ;; quickly looked up that way. The data is always a list (see example
73 ;; above) and each list element is indexed.
75 ;; Precious and tracked field names must be symbols. All other
76 ;; fields can be any other Emacs Lisp types.
80 (eval-when-compile (require 'ert))
81 (eval-when-compile (require 'cl))
83 (or (ignore-errors (progn
85 (require 'eieio-base)))
86 ;; gnus-fallback-lib/ from gnus/lisp/gnus-fallback-lib
88 (let ((load-path (cons (expand-file-name
89 "gnus-fallback-lib/eieio"
90 (file-name-directory (locate-library "gnus")))
93 (require 'eieio-base)))
95 "eieio not found in `load-path' or gnus-fallback-lib/ directory.")))
97 (defclass registry-db (eieio-persistent)
98 ((version :initarg :version
102 :documentation "The registry version.")
103 (max-hard :initarg :max-hard
107 :documentation "Never accept more than this many elements.")
108 (max-soft :initarg :max-soft
112 :documentation "Prune as much as possible to get to this size.")
113 (tracked :initarg :tracked
116 :documentation "The tracked (indexed) fields, a list of symbols.")
117 (precious :initarg :precious
120 :documentation "The precious fields, a list of symbols.")
121 (tracker :initarg :tracker
123 :documentation "The field tracking hashtable.")
126 :documentation "The data hashtable.")))
128 (defmethod initialize-instance :after ((this registry-db) slots)
129 "Set value of data slot of THIS after initialization."
130 (with-slots (data tracker) this
131 (unless (member :data slots)
132 (setq data (make-hash-table :size 10000 :rehash-size 2.0 :test 'equal)))
133 (unless (member :tracker slots)
134 (setq tracker (make-hash-table :size 100 :rehash-size 2.0)))))
136 (defmethod registry-lookup ((db registry-db) keys)
137 "Search for KEYS in the registry-db THIS.
138 Returns a alist of the key followed by the entry in a list, not a cons cell."
139 (let ((data (oref db :data)))
143 (when (gethash k data)
144 (list k (gethash k data))))
147 (defmethod registry-lookup-breaks-before-lexbind ((db registry-db) keys)
148 "Search for KEYS in the registry-db THIS.
149 Returns a alist of the key followed by the entry in a list, not a cons cell."
150 (let ((data (oref db :data)))
152 (loop for key in keys
153 when (gethash key data)
154 collect (list key (gethash key data))))))
156 (defmethod registry-lookup-secondary ((db registry-db) tracksym
158 "Search for TRACKSYM in the registry-db THIS.
159 When CREATE is not nil, create the secondary index hashtable if needed."
160 (let ((h (gethash tracksym (oref db :tracker))))
165 (make-hash-table :size 800 :rehash-size 2.0 :test 'equal)
167 (gethash tracksym (oref db :tracker))))))
169 (defmethod registry-lookup-secondary-value ((db registry-db) tracksym val
171 "Search for TRACKSYM with value VAL in the registry-db THIS.
172 When SET is not nil, set it for VAL (use t for an empty list)."
173 ;; either we're asked for creation or there should be an existing index
174 (when (or set (registry-lookup-secondary db tracksym))
175 ;; set the entry if requested,
177 (puthash val (if (eq t set) '() set)
178 (registry-lookup-secondary db tracksym t)))
179 (gethash val (registry-lookup-secondary db tracksym))))
181 (defun registry--match (mode entry check-list)
184 (let ((key (nth 0 (nth 0 check-list)))
185 (vals (cdr-safe (nth 0 check-list)))
187 (while (and key vals (not found))
188 (setq found (case mode
190 (member (car-safe vals) (cdr-safe (assoc key entry))))
192 (string-match (car vals)
195 (cdr-safe (assoc key entry))
197 vals (cdr-safe vals)))
199 (registry--match mode entry (cdr-safe check-list))))))
201 (defmethod registry-search ((db registry-db) &rest spec)
202 "Search for SPEC across the registry-db THIS.
203 For example calling with :member '(a 1 2) will match entry '((a 3 1)).
204 Calling with :all t (any non-nil value) will match all.
205 Calling with :regex '\(a \"h.llo\") will match entry '((a \"hullo\" \"bye\").
206 The test order is to check :all first, then :member, then :regex."
208 (let ((all (plist-get spec :all))
209 (member (plist-get spec :member))
210 (regex (plist-get spec :regex)))
211 (loop for k being the hash-keys of (oref db :data) using (hash-values v)
213 ;; :all non-nil returns all
216 (and member (registry--match :member v member))
218 (and regex (registry--match :regex v regex)))
221 (defmethod registry-delete ((db registry-db) keys assert &rest spec)
222 "Delete KEYS from the registry-db THIS.
223 If KEYS is nil, use SPEC to do a search.
224 Updates the secondary ('tracked') indices as well.
225 With assert non-nil, errors out if the key does not exist already."
226 (let* ((data (oref db :data))
228 (apply 'registry-search db spec)))
229 (tracked (oref db :tracked)))
232 (let ((entry (gethash key data)))
235 "Key %s does not exists in database" key))
236 ;; clean entry from the secondary indices
238 ;; is this tracked symbol indexed?
239 (when (registry-lookup-secondary db tr)
240 ;; for every value in the entry under that key...
241 (dolist (val (cdr-safe (assq tr entry)))
242 (let* ((value-keys (registry-lookup-secondary-value db tr val)))
243 (when (member key value-keys)
244 ;; override the previous value
245 (registry-lookup-secondary-value
247 ;; with the indexed keys MINUS the current key
248 ;; (we pass t when the list is empty)
249 (or (delete key value-keys) t)))))))
253 (defmethod registry-insert ((db registry-db) key entry)
254 "Insert ENTRY under KEY into the registry-db THIS.
255 Updates the secondary ('tracked') indices as well.
256 Errors out if the key exists already."
258 (assert (not (gethash key (oref db :data))) nil
259 "Key already exists in database")
261 (assert (< (registry-size db)
264 "max-hard size limit reached")
267 (puthash key entry (oref db :data))
269 ;; store the secondary indices
270 (dolist (tr (oref db :tracked))
271 ;; for every value in the entry under that key...
272 (dolist (val (cdr-safe (assq tr entry)))
273 (let* ((value-keys (registry-lookup-secondary-value db tr val)))
274 (pushnew key value-keys :test 'equal)
275 (registry-lookup-secondary-value db tr val value-keys))))
278 (defmethod registry-size ((db registry-db))
279 "Returns the size of the registry-db object THIS.
280 This is the key count of the :data slot."
281 (hash-table-count (oref db :data)))
283 (defmethod registry-prune ((db registry-db))
284 "Prunes the registry-db object THIS.
285 Removes only entries without the :precious keys."
286 (let* ((precious (oref db :precious))
287 (precious-p (lambda (entry-key) (cdr (memq (car entry-key) precious))))
288 (data (oref db :data))
289 (limit (oref db :max-soft))
290 (size (registry-size db))
291 (candidates (loop for k being the hash-keys of data
292 using (hash-values v)
293 when (notany precious-p v)
295 (candidates-count (length candidates))
296 ;; are we over max-soft?
297 (prune-needed (> size limit)))
299 ;; while we have more candidates than we need to remove...
300 (while (and (> candidates-count (- size limit)) candidates)
301 (decf candidates-count)
302 (setq candidates (cdr candidates)))
304 (registry-delete db candidates nil)))
306 (ert-deftest registry-instantiation-test ()
307 (should (registry-db "Testing")))
309 (ert-deftest registry-match-test ()
310 (let ((entry '((hello "goodbye" "bye") (blank))))
312 (message "Testing :regex matching")
313 (should (registry--match :regex entry '((hello "nye" "bye"))))
314 (should (registry--match :regex entry '((hello "good"))))
315 (should-not (registry--match :regex entry '((hello "nye"))))
316 (should-not (registry--match :regex entry '((hello))))
318 (message "Testing :member matching")
319 (should (registry--match :member entry '((hello "bye"))))
320 (should (registry--match :member entry '((hello "goodbye"))))
321 (should-not (registry--match :member entry '((hello "good"))))
322 (should-not (registry--match :member entry '((hello "nye"))))
323 (should-not (registry--match :member entry '((hello)))))
324 (message "Done with matching testing."))
326 (defun registry-make-testable-db (n &optional name file)
327 (let* ((db (registry-db
329 :file (or file "unused")
331 :max-soft 0 ; keep nothing not precious
332 :precious '(extra more-extra)
333 :tracked '(sender subject groups))))
335 (registry-insert db i `((sender "me")
336 (subject "about you")
337 (more-extra) ; empty data key should be pruned
338 ;; first 5 entries will NOT have this extra data
339 ,@(when (< 5 i) (list (list 'extra "more data")))
340 (groups ,(number-to-string i)))))
343 (ert-deftest registry-usage-test ()
345 (db (registry-make-testable-db n)))
346 (message "size %d" n)
347 (should (= n (registry-size db)))
348 (message "max-hard test")
349 (should-error (registry-insert db "new" '()))
350 (message "Individual lookup")
351 (should (= 58 (caadr (registry-lookup db '(1 58 99)))))
352 (message "Grouped individual lookup")
353 (should (= 3 (length (registry-lookup db '(1 58 99)))))
354 (message "Individual lookup (breaks before lexbind)")
356 (caadr (registry-lookup-breaks-before-lexbind db '(1 58 99)))))
357 (message "Grouped individual lookup (breaks before lexbind)")
359 (length (registry-lookup-breaks-before-lexbind db '(1 58 99)))))
361 (should (= n (length (registry-search db :all t))))
362 (should (= n (length (registry-search db :member '((sender "me"))))))
363 (message "Secondary index search")
364 (should (= n (length (registry-lookup-secondary-value db 'sender "me"))))
365 (should (equal '(74) (registry-lookup-secondary-value db 'groups "74")))
367 (should (registry-delete db '(1) t))
369 (message "Search after delete")
370 (should (= n (length (registry-search db :all t))))
371 (message "Secondary search after delete")
372 (should (= n (length (registry-lookup-secondary-value db 'sender "me"))))
374 (let* ((tokeep (registry-search db :member '((extra "more data"))))
375 (count (- n (length tokeep)))
376 (pruned (registry-prune db))
377 (prune-count (length pruned)))
378 (message "Expecting to prune %d entries and pruned %d"
380 (should (and (= count 5)
381 (= count prune-count))))
382 (message "Done with usage testing.")))
384 (ert-deftest registry-persistence-test ()
386 (tempfile (make-temp-file "registry-persistence-"))
387 (name "persistence tester")
388 (db (registry-make-testable-db n name tempfile))
390 (message "Saving to %s" tempfile)
391 (eieio-persistent-save db)
392 (setq size (nth 7 (file-attributes tempfile)))
393 (message "Saved to %s: size %d" tempfile size)
396 (insert-file-contents-literally tempfile)
397 (should (looking-at (concat ";; Object "
399 "\n;; EIEIO PERSISTENT OBJECT"))))
400 (message "Reading object back")
401 (setq back (eieio-persistent-read tempfile))
403 (message "Read object back: %d keys, expected %d==%d"
404 (registry-size back) n (registry-size db))
405 (should (= (registry-size back) n))
406 (should (= (registry-size back) (registry-size db)))
407 (delete-file tempfile))
408 (message "Done with persistence testing."))
411 ;;; registry.el ends here