Fix Gnus registry pruning and sorting, and rename file
[emacs.git] / lisp / gnus / registry.el
blobd086d642772491853a1dc6e9abfebf2231bb9cff
1 ;;; registry.el --- Track and remember data items by various fields
3 ;; Copyright (C) 2011-2014 Free Software Foundation, Inc.
5 ;; Author: Teodor Zlatanov <tzz@lifelogs.com>
6 ;; Keywords: data
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/>.
23 ;;; Commentary:
25 ;; This library provides a general-purpose EIEIO-based registry
26 ;; database with persistence, initialized with these fields:
28 ;; version: a float
30 ;; max-size: an integer, default 50000
32 ;; prune-factor: a float between 0 and 1, default 0.1
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. When
61 ;; the registry is pruned, any entries without the F2 field will be
62 ;; removed until the size is :max-size * :prune-factor _less_ than the
63 ;; maximum database size. No entries with the F2 field will be removed
64 ;; at PRUNE TIME, which means it may not be possible to prune back all
65 ;; the way to the target size.
67 ;; When an entry is inserted, the registry will reject new entries if
68 ;; they bring it over the :max-size limit, even if they have the F2
69 ;; field.
71 ;; The user decides which fields are "tracked", F1 for example. Any
72 ;; new entry is then indexed by all the tracked fields so it can be
73 ;; quickly looked up that way. The data is always a list (see example
74 ;; above) and each list element is indexed.
76 ;; Precious and tracked field names must be symbols. All other
77 ;; fields can be any other Emacs Lisp types.
79 ;;; Code:
81 (eval-when-compile (require 'cl))
83 (require 'eieio)
84 (require 'eieio-base)
86 ;; The version number needs to be kept outside of the class definition
87 ;; itself. The persistent-save process does *not* write to file any
88 ;; slot values that are equal to the default :initform value. If a
89 ;; database object is at the most recent version, therefore, its
90 ;; version number will not be written to file. That makes it
91 ;; difficult to know when a database needs to be upgraded.
92 (defvar registry-db-version 0.2
93 "The current version of the registry format.")
95 (defclass registry-db (eieio-persistent)
96 ((version :initarg :version
97 :initform nil
98 :type (or null float)
99 :documentation "The registry version.")
100 (max-size :initarg :max-size
101 :initform most-positive-fixnum
102 :type integer
103 :custom integer
104 :documentation "The maximum number of registry entries.")
105 (prune-factor
106 :initarg :prune-factor
107 :initform 0.1
108 :type float
109 :custom float
110 :documentation "Prune to \(:max-size * :prune-factor\) less
111 than the :max-size limit. Should be a float between 0 and 1.")
112 (tracked :initarg :tracked
113 :initform nil
114 :type t
115 :documentation "The tracked (indexed) fields, a list of symbols.")
116 (precious :initarg :precious
117 :initform nil
118 :type t
119 :documentation "The precious fields, a list of symbols.")
120 (tracker :initarg :tracker
121 :type hash-table
122 :documentation "The field tracking hashtable.")
123 (data :initarg :data
124 :type hash-table
125 :documentation "The data hashtable.")))
127 (defmethod initialize-instance :BEFORE ((this registry-db) slots)
128 "Check whether a registry object needs to be upgraded."
129 ;; Hardcoded upgrade routines. Version 0.1 to 0.2 requires the
130 ;; :max-soft slot to disappear, and the :max-hard slot to be renamed
131 ;; :max-size.
132 (let ((current-version
133 (and (plist-member slots :version)
134 (plist-get slots :version))))
135 (when (or (null current-version)
136 (eql current-version 0.1))
137 (setq slots
138 (plist-put slots :max-size (plist-get slots :max-hard)))
139 (setq slots
140 (plist-put slots :version registry-db-version))
141 (cl-remf slots :max-hard)
142 (cl-remf slots :max-soft))))
144 (defmethod initialize-instance :AFTER ((this registry-db) slots)
145 "Set value of data slot of THIS after initialization."
146 (with-slots (data tracker) this
147 (unless (member :data slots)
148 (setq data
149 (make-hash-table :size 10000 :rehash-size 2.0 :test 'equal)))
150 (unless (member :tracker slots)
151 (setq tracker (make-hash-table :size 100 :rehash-size 2.0)))))
153 (defmethod registry-lookup ((db registry-db) keys)
154 "Search for KEYS in the registry-db THIS.
155 Returns an alist of the key followed by the entry in a list, not a cons cell."
156 (let ((data (oref db :data)))
157 (delq nil
158 (mapcar
159 (lambda (k)
160 (when (gethash k data)
161 (list k (gethash k data))))
162 keys))))
164 (defmethod registry-lookup-breaks-before-lexbind ((db registry-db) keys)
165 "Search for KEYS in the registry-db THIS.
166 Returns an alist of the key followed by the entry in a list, not a cons cell."
167 (let ((data (oref db :data)))
168 (delq nil
169 (loop for key in keys
170 when (gethash key data)
171 collect (list key (gethash key data))))))
173 (defmethod registry-lookup-secondary ((db registry-db) tracksym
174 &optional create)
175 "Search for TRACKSYM in the registry-db THIS.
176 When CREATE is not nil, create the secondary index hashtable if needed."
177 (let ((h (gethash tracksym (oref db :tracker))))
178 (if h
180 (when create
181 (puthash tracksym
182 (make-hash-table :size 800 :rehash-size 2.0 :test 'equal)
183 (oref db :tracker))
184 (gethash tracksym (oref db :tracker))))))
186 (defmethod registry-lookup-secondary-value ((db registry-db) tracksym val
187 &optional set)
188 "Search for TRACKSYM with value VAL in the registry-db THIS.
189 When SET is not nil, set it for VAL (use t for an empty list)."
190 ;; either we're asked for creation or there should be an existing index
191 (when (or set (registry-lookup-secondary db tracksym))
192 ;; set the entry if requested,
193 (when set
194 (puthash val (if (eq t set) '() set)
195 (registry-lookup-secondary db tracksym t)))
196 (gethash val (registry-lookup-secondary db tracksym))))
198 (defun registry--match (mode entry check-list)
199 ;; for all members
200 (when check-list
201 (let ((key (nth 0 (nth 0 check-list)))
202 (vals (cdr-safe (nth 0 check-list)))
203 found)
204 (while (and key vals (not found))
205 (setq found (case mode
206 (:member
207 (member (car-safe vals) (cdr-safe (assoc key entry))))
208 (:regex
209 (string-match (car vals)
210 (mapconcat
211 'prin1-to-string
212 (cdr-safe (assoc key entry))
213 "\0"))))
214 vals (cdr-safe vals)))
215 (or found
216 (registry--match mode entry (cdr-safe check-list))))))
218 (defmethod registry-search ((db registry-db) &rest spec)
219 "Search for SPEC across the registry-db THIS.
220 For example calling with :member '(a 1 2) will match entry '((a 3 1)).
221 Calling with :all t (any non-nil value) will match all.
222 Calling with :regex '\(a \"h.llo\") will match entry '((a \"hullo\" \"bye\").
223 The test order is to check :all first, then :member, then :regex."
224 (when db
225 (let ((all (plist-get spec :all))
226 (member (plist-get spec :member))
227 (regex (plist-get spec :regex)))
228 (loop for k being the hash-keys of (oref db :data)
229 using (hash-values v)
230 when (or
231 ;; :all non-nil returns all
233 ;; member matching
234 (and member (registry--match :member v member))
235 ;; regex matching
236 (and regex (registry--match :regex v regex)))
237 collect k))))
239 (defmethod registry-delete ((db registry-db) keys assert &rest spec)
240 "Delete KEYS from the registry-db THIS.
241 If KEYS is nil, use SPEC to do a search.
242 Updates the secondary ('tracked') indices as well.
243 With assert non-nil, errors out if the key does not exist already."
244 (let* ((data (oref db :data))
245 (keys (or keys
246 (apply 'registry-search db spec)))
247 (tracked (oref db :tracked)))
249 (dolist (key keys)
250 (let ((entry (gethash key data)))
251 (when assert
252 (assert entry nil
253 "Key %s does not exist in database" key))
254 ;; clean entry from the secondary indices
255 (dolist (tr tracked)
256 ;; is this tracked symbol indexed?
257 (when (registry-lookup-secondary db tr)
258 ;; for every value in the entry under that key...
259 (dolist (val (cdr-safe (assq tr entry)))
260 (let* ((value-keys (registry-lookup-secondary-value
261 db tr val)))
262 (when (member key value-keys)
263 ;; override the previous value
264 (registry-lookup-secondary-value
265 db tr val
266 ;; with the indexed keys MINUS the current key
267 ;; (we pass t when the list is empty)
268 (or (delete key value-keys) t)))))))
269 (remhash key data)))
270 keys))
272 (defmethod registry-size ((db registry-db))
273 "Returns the size of the registry-db object THIS.
274 This is the key count of the :data slot."
275 (hash-table-count (oref db :data)))
277 (defmethod registry-full ((db registry-db))
278 "Checks if registry-db THIS is full."
279 (>= (registry-size db)
280 (oref db :max-size)))
282 (defmethod registry-insert ((db registry-db) key entry)
283 "Insert ENTRY under KEY into the registry-db THIS.
284 Updates the secondary ('tracked') indices as well.
285 Errors out if the key exists already."
287 (assert (not (gethash key (oref db :data))) nil
288 "Key already exists in database")
290 (assert (not (registry-full db))
292 "registry max-size limit reached")
294 ;; store the entry
295 (puthash key entry (oref db :data))
297 ;; store the secondary indices
298 (dolist (tr (oref db :tracked))
299 ;; for every value in the entry under that key...
300 (dolist (val (cdr-safe (assq tr entry)))
301 (let* ((value-keys (registry-lookup-secondary-value db tr val)))
302 (pushnew key value-keys :test 'equal)
303 (registry-lookup-secondary-value db tr val value-keys))))
304 entry)
306 (defmethod registry-reindex ((db registry-db))
307 "Rebuild the secondary indices of registry-db THIS."
308 (let ((count 0)
309 (expected (* (length (oref db :tracked)) (registry-size db))))
310 (dolist (tr (oref db :tracked))
311 (let (values)
312 (maphash
313 (lambda (key v)
314 (incf count)
315 (when (and (< 0 expected)
316 (= 0 (mod count 1000)))
317 (message "reindexing: %d of %d (%.2f%%)"
318 count expected (/ (* 100 count) expected)))
319 (dolist (val (cdr-safe (assq tr v)))
320 (let* ((value-keys (registry-lookup-secondary-value db tr val)))
321 (push key value-keys)
322 (registry-lookup-secondary-value db tr val value-keys))))
323 (oref db :data))))))
325 (defmethod registry-prune ((db registry-db) &optional sortfunc)
326 "Prunes the registry-db object DB.
328 Attempts to prune the number of entries down to \(*
329 :max-size :prune-factor\) less than the max-size limit, so
330 pruning doesn't need to happen on every save. Removes only
331 entries without the :precious keys, so it may not be possible to
332 reach the target limit.
334 Entries to be pruned are first sorted using SORTFUNC. Entries
335 from the front of the list are deleted first.
337 Returns the number of deleted entries."
338 (let ((size (registry-size db))
339 (target-size (- (oref db :max-size)
340 (* (oref db :max-size)
341 (oref db :prune-factor))))
342 candidates)
343 (if (> size target-size)
344 (progn
345 (setq candidates
346 (registry-collect-prune-candidates
347 db (- size target-size) sortfunc))
348 (length (registry-delete db candidates nil)))
349 0)))
351 (defmethod registry-collect-prune-candidates ((db registry-db) limit sortfunc)
352 "Collects pruning candidates from the registry-db object DB.
354 Proposes only entries without the :precious keys, and attempts to
355 return LIMIT such candidates. If SORTFUNC is provided, sort
356 entries first and return candidates from beginning of list."
357 (let* ((precious (oref db :precious))
358 (precious-p (lambda (entry-key)
359 (cdr (memq (car entry-key) precious))))
360 (data (oref db :data))
361 (candidates (cl-loop for k being the hash-keys of data
362 using (hash-values v)
363 when (notany precious-p v)
364 collect (cons k v))))
365 ;; We want the full entries for sorting, but should only return a
366 ;; list of entry keys.
367 (when sortfunc
368 (setq candidates (sort candidates sortfunc)))
369 (delq nil (cl-subseq (mapcar #'car candidates) 0 limit))))
371 (provide 'registry)
372 ;;; registry.el ends here