Class: Async::HTTP::Cache

Inherits:
Protocol::HTTP::Middleware
  • Object
show all
Defined in:
lib/async/http/cache.rb

Defined Under Namespace

Classes: Response

Constant Summary collapse

CACHE_CONTROL =
'cache-control'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, responses = {}) ⇒ Cache

Returns a new instance of Cache.



82
83
84
85
86
87
88
# File 'lib/async/http/cache.rb', line 82

def initialize(app, responses = {})
	super(app)
	
	@count = 0
	
	@responses = {}
end

Instance Attribute Details

#countObject (readonly)

Returns the value of attribute count.



90
91
92
# File 'lib/async/http/cache.rb', line 90

def count
  @count
end

Instance Method Details

#cachable?(request) ⇒ Boolean

Returns:

  • (Boolean)


96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/async/http/cache.rb', line 96

def cachable?(request)
	# We don't support caching requests which have a body:
	if request.body
		return false
	end
	
	# We can't cache upgraded requests:
	if request.protocol
		return false
	end
	
	# We only support caching GET and HEAD requests:
	if request.method == 'GET' || request.method == 'HEAD'
		return true
	end
	
	# Otherwise, we can't cache it:
	return false
end

#call(request) ⇒ Object



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/async/http/cache.rb', line 128

def call(request)
	key = self.key(request)
	
	if response = @responses[key]
		Async.logger.debug(self) {"Cache hit for #{key}..."}
		@count += 1
		
		if response.expired?
			@responses.delete(key)
			Async.logger.debug(self) {"Cache expired for #{key}..."}
		else
			# Create a dup of the response:
			return response.dup
		end
	end
	
	if cachable?(request)
		Async.logger.debug(self) {"Updating cache for #{key}..."}
		return wrap(request, key, super)
	else
		return super
	end
end

#key(request) ⇒ Object



92
93
94
# File 'lib/async/http/cache.rb', line 92

def key(request)
	[request.authority, request.method, request.path]
end

#wrap(request, key, response) ⇒ Object



116
117
118
119
120
121
122
123
124
125
126
# File 'lib/async/http/cache.rb', line 116

def wrap(request, key, response)
	Body::Cacheable.wrap(response) do |response, body|
		response = Response.new(response, body)
		
		if response.cachable?
			@responses[key] = response
		end
	end
	
	return response
end