Search code examples
ruby-on-railsrubyworklingstarling-server

Workling worker cannot find newly added record


I'm using Starling and Workling to process background tasks in my application, a Swoopo-style auction site. In this case the background task is a notification system that monitors auctions and notifies the winner. The monitor is invoked upon creation of the auction object. My problem is that my monitoring code can't find the auction it's supposed to monitor. Here's the code:

The unit test that fails:

class AuctionTest < ActiveSupport::TestCase
  test "are monitored when created" do
    auction = Auction.new(
      :name => "A TV",
      :markdown => "A large TV",
      :starting_bid => 0.01,
      :bid_increment => 0.01,
      :starts_at => Time.now(),
      :ends_at => Time.now() + 5.seconds,
      :active => true
    )
    auction.save
    Bid.place(@current_user, auction)

    sleep(10) #when bids are placed, time is added to the end of the auction so wait

    assert auction.won?
    assert_equal @current_user.id, auction.winner_id
  end
end

The worker code:

class AuctionsWorker < Workling::Base
  def monitor(options)
    active = true
    ends_at = options[:original_ends_at]
    while active
      auction = Auction.find(options[:auction_id]) #this is the record that cannot be found
      if auction.won?
        active = false
        winner = User.find(auction.high_bidder).id
        auction.update_attribute(:winner_id, winner)
      else
        until Time.now() >= ends_at
          sleep(1)
        end
      end
    end
  end
end

The code that calls the worker:

class Auction < ActiveRecord::Base
  def after_create
    AuctionsWorker.asynch_monitor(:auction_id => self.id, :original_ends_at => self.ends_at) if self.active?
  end
end

Every time I run the test, I receive an error telling me that the auction supplied to the worker can't be found.

Does anyone have any ideas? I'm using rails 2.3.5, sqlite3 and the latest Starling, Workling, and all other associated gems on a Mac OSX 10.6.2 Macbook Pro if it helps.

Thank you for all input.


Solution

  • You should get downvoted for creating a "swoopo-style" auction, and I feel dirty for helping you.

    after_create() Is called after Base.save on new objects that haven‘t been saved yet (no record exists)

    so after_create is a bit of a misnomer - the record hasn't really been created yet.

    http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html#M002142

    You could add your own id field and have the workling process search the db for that id, sleeping a few seconds every time it doesn't find it (up to some preset failure limit).

    Alternatively - you could try one of the several after_commit plugins that are on github that get called after the database has been updated.

    Here's one:

    http://github.com/delynn/after_commit