Skip to content

Commit b184f2e

Browse files
Keep controller start idempotent
Assisted-By: devx/3236e566-7538-432e-a30a-2bdf37265ed4
1 parent b8b72d5 commit b184f2e

2 files changed

Lines changed: 34 additions & 5 deletions

File tree

lib/async/container/controller.rb

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -181,16 +181,21 @@ def stop(graceful = @graceful_stop)
181181
# This is equivalent to a blue-green deployment.
182182
def start(restart: false)
183183
old_container = nil
184+
new_container = nil
184185

185186
@guard.synchronize do
186-
if @container && restart
187-
@notify&.restarting!
188-
189-
Console.info(self, "Restarting container...")
187+
if @container
188+
if restart
189+
@notify&.restarting!
190+
191+
Console.info(self, "Restarting container...")
192+
else
193+
return @container
194+
end
190195
else
191196
Console.info(self, "Starting container...")
192197
end
193-
198+
194199
container = self.create_container
195200

196201
begin
@@ -217,6 +222,7 @@ def start(restart: false)
217222
# The following swap should be atomic:
218223
old_container = @container
219224
@container = container
225+
new_container = container
220226
container = nil
221227

222228
@notify&.ready!(size: @container.size, status: "Running with #{@container.size} children.")
@@ -234,6 +240,8 @@ def start(restart: false)
234240
Console.info(self, "Stopping old container...")
235241
old_container.stop(@graceful_stop)
236242
end
243+
244+
return new_container
237245
end
238246

239247
# Reload the existing container. Children instances will be reloaded using `SIGHUP`.

test/async/container/controller.rb

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,27 @@ def controller.setup(container)
155155
controller.stop
156156
end
157157

158+
it "does not restart an already running container" do
159+
count = 0
160+
161+
controller.define_singleton_method(:setup) do |container|
162+
count += 1
163+
164+
container.spawn do |instance|
165+
instance.ready!
166+
sleep
167+
end
168+
end
169+
170+
first = controller.start
171+
second = controller.start
172+
173+
expect(second).to be == first
174+
expect(count).to be == 1
175+
176+
controller.stop(false)
177+
end
178+
158179
it "propagates exceptions" do
159180
def controller.setup(container)
160181
raise "Boom!"

0 commit comments

Comments
 (0)