travels.lisp 13 KB

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