An authentication server
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

98 satır
1.8 KiB

5 yıl önce
  1. require "sqlite3"
  2. require "../config.cr"
  3. class CacheLRU
  4. def initialize
  5. @store = Hash(String, Tuple(Time, User)).new
  6. @mutex = Mutex.new
  7. @cache_limit = 5000
  8. end
  9. def try(pair) : User | Nil
  10. @mutex.synchronize do
  11. if @store.has_key?(pair)
  12. return @store[pair][1]
  13. else return nil
  14. end
  15. end
  16. end
  17. def push(pair, data)
  18. @mutex.synchronize do
  19. @store[pair] = Tuple.new(Time.now+Time::Span.new(1,0,0), data)
  20. if(@store.size > @cache_limit)
  21. clean
  22. end
  23. end
  24. end
  25. def clean
  26. @mutex.synchronize do
  27. curr = Time.now
  28. @store.reject! do |k, v|
  29. return v[0]>curr
  30. end
  31. end
  32. end
  33. def invalidate(pair)
  34. @mutex.synchronize do
  35. @store.reject! pair
  36. end
  37. end
  38. end
  39. class KVStore
  40. property database : DB::Database
  41. property st_fetch : DB::PoolPreparedStatement
  42. property st_push : DB::PoolPreparedStatement
  43. property cache : CacheLRU
  44. def initialize
  45. @database = DB.open(Statics.data_path)
  46. @database.exec "create table if not exists kv (k TEXT PRIMARY KEY, v TEXT);"
  47. @st_fetch = DB::PoolPreparedStatement.new @database, "select v from kv where k=?;"
  48. @st_push = DB::PoolPreparedStatement.new @database, "insert into kv(k,v) values(?,?) on conflict(k) do update set v=?;"
  49. @cache = CacheLRU.new
  50. end
  51. def fetch(key : String) : User | Nil
  52. begin
  53. f = @cache.try(key)
  54. if(f.nil?)
  55. v = @st_fetch.scalar(key)
  56. u = User.from_json v.to_s
  57. @cache.push(key, u)
  58. if(v.nil?)
  59. return nil
  60. else
  61. return u
  62. end
  63. else
  64. return f
  65. end
  66. rescue ex
  67. return nil
  68. end
  69. end
  70. def fetch!(key : String) : User
  71. fetch(key).not_nil!
  72. end
  73. def push(key : String, value : String)
  74. @cache.invalidate key
  75. @st_push.exec(key, value, value)
  76. end
  77. def transaction()
  78. @database.transaction do |tx|
  79. yield self
  80. end
  81. end
  82. def self.access
  83. @@instance ||= new
  84. end
  85. end