Browse Source

#8 worker added

Tangent 4 years ago
parent
commit
624bd9c2f6
3 changed files with 36 additions and 1 deletions
  1. 1
    1
      app.moon
  2. 5
    0
      nginx.conf
  3. 30
    0
      worker.moon

+ 1
- 1
app.moon View File

@@ -68,7 +68,7 @@ class extends lapis.Application
68 68
     if tag_pattern != tag_pattern\lower!
69 69
       return redirect_to: @url_for "tag", name: escape(tag_pattern\lower!), order: @order, asc_desc: @asc_desc, page: @page
70 70
     tag_pattern = escape_literal tag_pattern
71
-    tag_pattern = "'% " .. tag_pattern\sub(2, -2) .. " %'"
71
+    tag_pattern = "'% #{tag_pattern\sub 2, -2} %'"
72 72
 
73 73
     tracks = Tracks\paginated "WHERE tags LIKE #{tag_pattern} ORDER BY #{escape_identifier @order} #{@asc_desc}", per_page: 32
74 74
     @last_page = 1

+ 5
- 0
nginx.conf View File

@@ -11,6 +11,11 @@ http {
11 11
   charset UTF-8;
12 12
   include mime.types;
13 13
 
14
+  lua_shared_dict worker 5k;
15
+  init_worker_by_lua '
16
+    require("worker")
17
+  ';
18
+
14 19
   server {
15 20
     listen ${{PORT}};
16 21
     lua_code_cache ${{CODE_CACHE}};

+ 30
- 0
worker.moon View File

@@ -0,0 +1,30 @@
1
+lock = require "resty.lock"
2
+
3
+import Tags, Tracks from require "models"
4
+import escape_literal from require "lapis.db"
5
+
6
+add_job = (interval, name, fn, init) ->
7
+  run = (premature, arg) ->
8
+    if premature return
9
+
10
+    thread_lock = lock\new "worker". { timeout: 0, exptime: interval }
11
+    if thread_lock\lock "t#{name}"
12
+
13
+      time_lock = lock\new "worker", { exptime: interval }
14
+      if time_lock\lock "t#{name}"
15
+        arg = fn(arg)
16
+        thread_lock\unlock!
17
+    ngx.timer.at(interval, run, arg)
18
+  ngx.timer.at(0, run, init)
19
+
20
+update_tag_counts = (id=1) ->
21
+  if tag = Tags\find(:id)
22
+    tag_pattern = escape_literal tag.name
23
+    tag_pattern = "'% #{tag_pattern\sub 2, -2} %'"
24
+    count = Tracks\count "tags LIKE #{tag_pattern}"
25
+    tag\update(:count)
26
+    next_tag = Tags\select "WHERE id > ? ORDER BY id ASC LIMIT 1", id
27
+    if next_tag = next_tag[1]
28
+      return next_tag.id
29
+
30
+add_job 60, "tags", update_tag_counts