I intend to use this privately for music organization.

worker.moon 1004B

123456789101112131415161718192021222324252627282930313233
  1. lock = require "resty.lock"
  2. import Tags, Tracks from require "models"
  3. import escape_literal from require "lapis.db"
  4. next_id = (id=0) ->
  5. next_tag = Tags\select "WHERE id > ? ORDER BY id ASC LIMIT 1", id
  6. unless next_tag
  7. next_tag = Tags\select "WHERE id > '0' ORDER BY id ASC LIMIT 1"
  8. if next_tag
  9. return next_tag[1].id
  10. update_tag_counts = (premature, tag_id) ->
  11. if premature return
  12. thread_lock = lock\new "worker", { timeout: 0, exptime: 2 }
  13. if thread_lock\lock "update_tag_counts.thread"
  14. time_lock = lock\new "worker", { exptime: 2 }
  15. if time_lock\lock "update_tag_counts.time"
  16. if tag_id
  17. if tag = Tags\find id: tag_id
  18. tag_pattern = escape_literal tag.name
  19. tag_pattern = "'% #{tag_pattern\sub 2, -2} %'"
  20. count = Tracks\count "tags LIKE #{tag_pattern}"
  21. tag\update(:count)
  22. tag_id = next_id(tag_id) or tag_id
  23. thread_lock\unlock!
  24. ngx.timer.at(2, update_tag_counts, tag_id)
  25. ngx.timer.at(0, update_tag_counts)