Skip to content

Instantly share code, notes, and snippets.

@yocontra
Created August 7, 2012 02:39
Show Gist options
  • Save yocontra/3280895 to your computer and use it in GitHub Desktop.
Save yocontra/3280895 to your computer and use it in GitHub Desktop.
DSTM via warlock demo
###
Network workflow:
Client connects
Client creates transaction
Server sends 'sync' with root object
Client runs transaction
if .retry() called
Client listens for 'sync' message then runs transaction again
else
Client calls .done() after transaction is complete
Client sends 'transaction' with transaction id and transaction log
if log doesnt match
Server sends 'failed' with transaction id
Client calls .retry()
else
Server sends 'sync' with root object to all clients
Server sends 'complete' with transaction id
Client returns callback for transaction
###
insertMoney = ->
checks = @get 'money.checks'
if checks.length is 0
# retry will halt the transaction until the next transaction then start again
@retry()
else
# incr is sugar for @set 'money.dollars', @get('money.dollars')+check.value
@incr 'money.dollars', check.value for check in checks
buyStock = ->
dollars = @get 'money.dollars'
appleStock = @get 'stock.apple.price'
return @abort() if dollars < appleStock
stockToBuy = dollars / appleStock
stocks = {type: 'Apple'} for i in [0..stockToBuy]
# append is sugar for @set 'stock.mine', @get('stock.mine').append stocks
@append 'stock.mine', stocks
sellStock = ->
dollars = @get 'money.dollars'
appleStock = @get 'stock.apple.price'
return @abort() if dollars < appleStock
myStocks = @get 'stock.mine'
@set 'stock.mine', (stock for stock in myStocks when stock.type isnt 'Apple')
@incr 'money.dollars', (myStocks.length - @get('stock.mine').length)*appleStock
trans = lock.atomic insertMoney, buyStock, sellStock
trans.run (err) ->
console.log err if err?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment