litestack 0.1.5 → 0.1.7

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,4 +1,5 @@
1
1
  require 'sqlite3'
2
+ require 'hiredis'
2
3
 
3
4
  module Litesupport
4
5
 
@@ -11,6 +12,11 @@ module Litesupport
11
12
  @env ||= detect_environment
12
13
  end
13
14
 
15
+ def self.max_contexts
16
+ return 50 if environment == :fiber || environment == :polyphony
17
+ 5
18
+ end
19
+
14
20
  # identify which environment we are running in
15
21
  # we currently support :fiber, :polyphony, :iodine & :threaded
16
22
  # in the future we might want to expand to other environments
@@ -33,6 +39,18 @@ module Litesupport
33
39
  # we should never reach here
34
40
  end
35
41
 
42
+ def self.detect_context
43
+ if environment == :fiber || environment == :poylphony
44
+ Fiber.current.storage
45
+ else
46
+ Thread.current
47
+ end
48
+ end
49
+
50
+ def self.context
51
+ @ctx ||= detect_context
52
+ end
53
+
36
54
  # switch the execution context to allow others to run
37
55
  def self.switch
38
56
  if self.environment == :fiber
@@ -43,7 +61,7 @@ module Litesupport
43
61
  Thread.current.switch_fiber
44
62
  true
45
63
  else
46
- # do nothing in case of thread, switching will auto-happen
64
+ #Thread.pass
47
65
  false
48
66
  end
49
67
  end
@@ -71,7 +89,64 @@ module Litesupport
71
89
  db = SQLite3::Database.new(path)
72
90
  db.busy_handler{ switch || sleep(0.001) }
73
91
  db.journal_mode = "WAL"
92
+ db.instance_variable_set(:@stmts, {})
93
+ class << db
94
+ attr_reader :stmts
95
+ end
74
96
  db
75
97
  end
76
98
 
99
+ class Mutex
100
+
101
+ def initialize
102
+ @mutex = Thread::Mutex.new
103
+ end
104
+
105
+ def synchronize(&block)
106
+ if Litesupport.environment == :threaded || Litesupport.environment == :iodine
107
+ @mutex.synchronize{ block.call }
108
+ else
109
+ block.call
110
+ end
111
+ end
112
+
113
+ end
114
+
115
+ class Pool
116
+
117
+ def initialize(count, &block)
118
+ @count = count
119
+ @block = block
120
+ @resources = []
121
+ @mutex = Litesupport::Mutex.new
122
+ @count.times do
123
+ resource = @mutex.synchronize{ block.call }
124
+ @resources << [resource, :free]
125
+ end
126
+ end
127
+
128
+ def acquire
129
+ acquired = false
130
+ result = nil
131
+ while !acquired do
132
+ @mutex.synchronize do
133
+ if resource = @resources.find{|r| r[1] == :free }
134
+ resource[1] = :busy
135
+ begin
136
+ result = yield resource[0]
137
+ rescue Exception => e
138
+ raise e
139
+ ensure
140
+ resource[1] = :free
141
+ acquired = true
142
+ end
143
+ end
144
+ end
145
+ sleep 0.001 unless acquired
146
+ end
147
+ result
148
+ end
149
+
150
+ end
151
+
77
152
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Litestack
4
- VERSION = "0.1.5"
4
+ VERSION = "0.1.7"
5
5
  end