travels.lisp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. (in-package :travels)
  2. (defun update-indexes (storage old new)
  3. (declare (optimize (speed 3) (safety 0))
  4. (type hash-table storage)
  5. (type (or null list) old)
  6. (type (or null list) new))
  7. (let ((id (or (getf old :|id|) (getf new :|id|)))
  8. (old-user (the (or null fixnum) (getf old :|user|)))
  9. (new-user (the (or null fixnum) (getf new :|user|)))
  10. (old-loc (the (or null fixnum) (getf old :|location|)))
  11. (new-loc (the (or null fixnum) (getf new :|location|))))
  12. (labels ((update (s o n)
  13. (when o (setf (gethash o s) (remove id (gethash o s))))
  14. (when n (push id (gethash n s)))))
  15. (when (or (null new)
  16. (null old)
  17. (and new-user (not (= old-user new-user))))
  18. (update (or (gethash :user-visits storage)
  19. (setf (gethash :user-visits storage) (make-hash-table)))
  20. old-user new-user))
  21. (when (or (null new) (null old)
  22. (and new-loc (not (= old-loc new-loc))))
  23. (update (or (gethash :location-visits storage)
  24. (setf (gethash :location-visits storage) (make-hash-table)))
  25. old-loc new-loc)))))
  26. (defun loads (bytes)
  27. (declare (optimize (speed 3) (safety 0))
  28. (type (simple-array (unsigned-byte 8) (*)) bytes))
  29. (jojo:parse (trivial-utf-8:utf-8-bytes-to-string bytes)))
  30. (defun dumps (data)
  31. (declare (optimize (speed 3) (safety 0))
  32. (type (or null list) data))
  33. (trivial-utf-8:string-to-utf-8-bytes (jojo:to-json data)))
  34. (defun load-data (pathname)
  35. (declare (optimize (speed 3) (safety 0)))
  36. (let ((storage (make-hash-table)))
  37. (zip:with-zipfile (zip pathname)
  38. (zip:do-zipfile-entries (name entry zip)
  39. (let ((data (loads (zip:zipfile-entry-contents entry))))
  40. (destructuring-bind (entity elements) data
  41. (let ((entity-storage
  42. (or (gethash entity storage)
  43. (setf (gethash entity storage)
  44. (make-hash-table :size (length (the list elements)))))))
  45. (loop for item in elements
  46. do (setf (gethash (getf item :|id|) entity-storage)
  47. (dumps item))
  48. when (eq entity :|visits|)
  49. do (update-indexes storage nil item)))))))
  50. storage))
  51. (defvar *storage* nil "data store")
  52. (defvar *storage-users* nil "users store")
  53. (defvar *storage-locations* nil "locations store")
  54. (defvar *storage-visits* nil "visits store")
  55. (let ((keyword-package (find-package :keyword)))
  56. (defun getkey (place indicator)
  57. (declare
  58. (optimize (speed 3) (safety 0))
  59. (type list place)
  60. (type symbol indicator))
  61. (intern (getf place indicator) keyword-package)))
  62. (defparameter +400+ '(400 nil #.(trivial-utf-8:string-to-utf-8-bytes "400")))
  63. (defparameter +404+ '(404 nil #.(trivial-utf-8:string-to-utf-8-bytes "404")))
  64. (defparameter +200-empty+ '(200 (:content-type "application/json")
  65. #.(trivial-utf-8:string-to-utf-8-bytes "{}")))
  66. (defun 200-json (data)
  67. (declare (optimize (speed 3) (safety 0))
  68. (type list data))
  69. `(200 (:content-type "application/json") ,(dumps data)))
  70. (defun get-entity (params)
  71. (declare (optimize (speed 3) (safety 0)))
  72. (let ((id (parse-integer (getf params :id) :junk-allowed t))
  73. (entity (the symbol (getkey params :entity))))
  74. (if id
  75. (case entity
  76. ((:|users| :|visits| :|locations|)
  77. (let ((entity (gethash (the fixnum id) (gethash (the symbol entity) *storage*))))
  78. (if entity
  79. `(200 (:content-type "application/json") ,entity)
  80. +404+)))
  81. (otherwise +404+))
  82. +404+)))
  83. (defun validate-item (item)
  84. (declare (type (or null list) item)
  85. (optimize (speed 3) (safety 0)))
  86. (when item
  87. (loop for (k v) on item by #'cddr
  88. unless v return nil
  89. ; when (and (eq k :|id|) (not (integerp v))) return nil
  90. ; when (and (eq k :|distance|) (not (integerp v))) return nil
  91. ; when (and (eq k :|visited_at|) (not (integerp v))) return nil
  92. ; when (and (eq k :|country|) (or (not (stringp v)) (> (length v) 50))) return nil
  93. ; when (and (eq k :|city|) (or (not (stringp v)) (> (length v) 50))) return nil
  94. ; when (and (eq k :|mark|) (or (not (integerp v)) (not (<= 0 (the fixnum v) 5)))) return nil
  95. ; when (and (eq k :|user|) (or (not (integerp v)) (not (gethash v *storage-users*)))) return nil
  96. ; when (and (eq k :|location|) (or (not (integerp v)) (not (gethash v *storage-locations*)))) return nil
  97. finally (return t))))
  98. (defun post-entity (params)
  99. (declare (optimize (speed 3) (safety 0)))
  100. (let ((id (parse-integer (getf params :id) :junk-allowed t))
  101. (entity (getkey params :entity)))
  102. (if (or id (string= (the simple-string (getf params :id)) "new"))
  103. (case entity
  104. ((:|users| :|visits| :|locations|)
  105. (handler-case
  106. (let* ((body (trivial-utf-8:read-utf-8-string
  107. (getf myway:*env* :raw-body)
  108. :stop-at-eof t))
  109. (item (jojo:parse (coerce body 'simple-string)))
  110. (entity-storage (gethash entity *storage*)))
  111. (if (validate-item item)
  112. (let ((item-id (getf item :|id|)))
  113. (if id
  114. (if item-id +400+
  115. (let ((existing-raw (gethash id entity-storage)))
  116. (if existing-raw
  117. (let ((existing (loads existing-raw)))
  118. (when (eq entity :|visits|)
  119. (update-indexes *storage* existing item))
  120. (loop for (k v) on item by #'cddr
  121. do (setf (getf existing k) v))
  122. (setf (gethash id entity-storage)
  123. (dumps existing))
  124. +200-EMPTY+)
  125. +404+)))
  126. (let ((e (gethash item-id entity-storage)))
  127. (if e +400+
  128. (progn
  129. (when (eq entity :|visits|)
  130. (update-indexes *storage* nil item))
  131. (setf (gethash item-id entity-storage)
  132. (dumps item))
  133. +200-EMPTY+)))))
  134. +400+))
  135. ))
  136. (othewise +404+))
  137. +400+)))
  138. (defun aget (place indicator &key (test #'equal))
  139. (declare (type list place)
  140. (type (or string symbol) indicator)
  141. (type function test)
  142. (optimize (speed 3) (safety 0)))
  143. (cdr (assoc indicator place :test test)))
  144. (defun may-integer (string)
  145. (declare (type (or null string) string))
  146. (when string
  147. (parse-integer string)))
  148. (defun matching-location (location country to-distance)
  149. (and (or (not country) (equal (getf location :|country|) country))
  150. (or (not to-distance) (< (getf location :|distance|) to-distance))))
  151. (defun matching-visit (visit from-date to-date)
  152. (and (or (not from-date) (> (getf visit :|visited_at|) from-date))
  153. (or (not to-date) (< (getf visit :|visited_at|) to-date))))
  154. (defun user-visits (params)
  155. (declare (optimize (speed 3) (safety 0))
  156. (type list params))
  157. (let ((id (parse-integer (getf params :id) :junk-allowed t)))
  158. (if id
  159. (let ((user (gethash id *storage-users*)))
  160. (if user
  161. (handler-case
  162. (let* ((user-visit-ids (gethash id (gethash :user-visits *storage*)))
  163. (query-string (getf myway:*env* :query-string))
  164. (query-params (and query-string (quri:url-decode-params query-string))))
  165. (let ((from-date (may-integer (aget query-params "fromDate")))
  166. (to-date (may-integer (aget query-params "toDate")))
  167. (to-distance (may-integer (aget query-params "toDistance")))
  168. (country (the (or null string) (aget query-params "country"))))
  169. ;; (assert (or (null country) (<= (length country) 50)))
  170. ;; TODO: Smarter indexes
  171. (let ((user-visits (loop for v-id in user-visit-ids
  172. for visit = (loads (gethash v-id *storage-visits*))
  173. for loc = (loads (gethash (getf visit :|location|) *storage-locations*))
  174. when (and visit (matching-visit visit from-date to-date))
  175. when (and loc (matching-location loc country to-distance))
  176. collect (list :|mark| (getf visit :|mark|)
  177. :|visited_at| (getf visit :|visited_at|)
  178. :|place| (getf loc :|place|)))))
  179. (200-json (list :|visits|
  180. (sort (the list user-visits)
  181. #'< :key (lambda (v) (getf v :|visited_at|))))))))
  182. (error () +400+))
  183. +404+))
  184. +404+)))
  185. (defun smart-f (arg &optional digits)
  186. (with-output-to-string (s)
  187. (prin1 (cond ((= (round arg) arg) (round arg))
  188. (digits (float (/ (round (* arg (expt 10 digits)))
  189. (expt 10 digits))))
  190. (t arg))
  191. s)))
  192. (defvar *unix-epoch-difference*
  193. (encode-universal-time 0 0 0 1 1 1970 0))
  194. (defvar *year*
  195. (round (* 60 60 24 365.25)))
  196. (defun universal-to-unix-time (universal-time)
  197. (- universal-time *unix-epoch-difference*))
  198. (defun unix-to-universal-time (unix-time)
  199. (+ unix-time *unix-epoch-difference*))
  200. (defun get-unix-time ()
  201. (universal-to-unix-time (get-universal-time)))
  202. (defmethod jojo::%to-json ((ratio ratio))
  203. (jojo:%write-string (smart-f ratio 5)))
  204. (defun matching-user (user from-age to-age gender now)
  205. (let ((age (/ (- now (getf user :|birth_date|)) *year*)))
  206. (and (or (not gender) (equal (getf user :|gender|) gender))
  207. (or (not from-age) (> age from-age))
  208. (or (not to-age) (< age to-age)))))
  209. (defun location-avg-mark (params)
  210. (declare (optimize (speed 3) (safety 0))
  211. (type list params))
  212. (let ((id (parse-integer (getf params :id) :junk-allowed t)))
  213. (if id
  214. (let ((location (gethash id (gethash :|locations| *storage*))))
  215. (if location
  216. (handler-case
  217. (let* ((location-visit-ids (gethash id (gethash :location-visits *storage*)))
  218. (query-string (getf myway:*env* :query-string))
  219. (query-params (and query-string (quri:url-decode-params query-string))))
  220. (let ((from-date (may-integer (aget query-params "fromDate")))
  221. (to-date (may-integer (aget query-params "toDate")))
  222. (now (get-unix-time))
  223. (from-age (may-integer (aget query-params "fromAge")))
  224. (to-age (may-integer (aget query-params "toAge")))
  225. (gender (the (or null string) (aget query-params "gender"))))
  226. (assert (or (null gender) (string= gender "m") (string= gender "f")))
  227. (multiple-value-bind (s c)
  228. (loop
  229. with sum-marks of-type fixnum = 0
  230. with count-marks of-type fixnum = 0
  231. for v-id in location-visit-ids
  232. for visit = (loads (gethash v-id *storage-visits*))
  233. for user = (loads (gethash (getf visit :|user|) *storage-users*))
  234. when (and visit (matching-visit visit from-date to-date))
  235. when (and user (matching-user user from-age to-age gender now))
  236. do (setf sum-marks (+ sum-marks (the fixnum (getf visit :|mark|)))
  237. count-marks (1+ count-marks))
  238. finally (return (values sum-marks count-marks)))
  239. (200-json (list :|avg| (if (zerop c) 0.0 (/ s c)))))))
  240. (error () +400+))
  241. +404+))
  242. +404+)))
  243. (defvar *mapper* (myway:make-mapper))
  244. (myway:connect *mapper* "/:entity/:id" 'post-entity :method :post)
  245. (myway:connect *mapper* "/:entity/:id" 'get-entity)
  246. (myway:connect *mapper* "/users/:id/visits" 'user-visits)
  247. (myway:connect *mapper* "/locations/:id/avg" 'location-avg-mark)
  248. (myway:connect *mapper* "*" (lambda (p) (declare (ignore p)) +404+))
  249. (defun main (&rest args
  250. &key
  251. (data "data.zip")
  252. (address "0.0.0.0")
  253. (port 5000)
  254. (debug nil)
  255. (use-thread nil) &allow-other-keys)
  256. (setf *storage* (load-data data))
  257. (setf *storage-users* (gethash :|users| *storage*)
  258. *storage-locations* (gethash :|locations| *storage*)
  259. *storage-visits* (gethash :|visits| *storage*))
  260. #+sbcl (sb-ext:gc :full t)
  261. (room)
  262. (format t "Loaded ~A~%" data)
  263. (apply #'clack:clackup
  264. (myway:to-app *mapper*)
  265. :server :woo
  266. :address address
  267. :port port
  268. :debug debug
  269. :use-default-middlewares nil
  270. :use-thread use-thread
  271. (alexandria:remove-from-plist args :data :address :port :debug :use-thread)))