Exemplo n.º 1
0
// When the auction has completed, perform the following logic.
func CloseAuction(offerId int, bid *m.Bid) {
	auctionMap.Remove(offerId)

	// Check if the broker has enough inventory
	offerKeyId := fmt.Sprintf("%s:%d", OFFERS, offerId)
	offerKey, _ := as.NewKey(NAMESPACE, OFFERS, offerKeyId)
	offerRec, _ := db.Get(readPolicy, offerKey)
	sellerId := offerRec.Bins["broker_id"].(int)

	// add to buyer's inventory and reduce credit
	buyerKeyId := fmt.Sprintf("%s:%d", BROKERS, bid.BrokerId)
	buyerKey, _ := as.NewKey(NAMESPACE, BROKERS, buyerKeyId)
	db.Operate(writePolicy, buyerKey,
		as.AddOp(as.NewBin(offerRec.Bins["ticker"].(string), offerRec.Bins["quantity"].(int))),
		as.AddOp(as.NewBin("credit", -1*offerRec.Bins["quantity"].(int)*int(bid.Price))),
	)

	// reduce seller's inventory and add to credit
	sellerKeyId := fmt.Sprintf("%s:%d", BROKERS, sellerId)
	sellerKey, _ := as.NewKey(NAMESPACE, BROKERS, sellerKeyId)
	db.Operate(writePolicy, sellerKey,
		as.AddOp(as.NewBin(offerRec.Bins["ticker"].(string), -1*offerRec.Bins["quantity"].(int))),
		as.AddOp(as.NewBin("credit", offerRec.Bins["quantity"].(int)*int(bid.Price))),
	)

	// mark the bid as winner
	bidKeyId := fmt.Sprintf("%s:%d", BIDS, bid.Id)
	bidKey, _ := as.NewKey(NAMESPACE, BIDS, bidKeyId)
	db.Put(writePolicy, bidKey, as.BinMap{"winner": 1})
	db.Put(writePolicy, offerKey, as.BinMap{"finished": 1, "winner": bid.Id})
}
func send(cache []Event) {
	fmt.Println("sending %s", len(cache))
	for index, element := range cache {
		_ = index
		//fmt.Println(element.id, element.event, element.value)
		//fmt.Println(index)
		key, _ := as.NewKey("test", "totals", "total_votes")
		ops := []*as.Operation{
			as.AddOp(as.NewBin("total_votes", 1)), // add the value of the bin to the existing value
			as.GetOp(),                            // get the value of the record after all operations are executed
		}

		_, _ = client.Operate(nil, key, ops...)

		key, _ = as.NewKey("test", "totals", element.value)
		ops = []*as.Operation{
			as.AddOp(as.NewBin(element.value, 1)), // add the value of the bin to the existing value
			as.GetOp(),                            // get the value of the record after all operations are executed
		}

		_, _ = client.Operate(nil, key, ops...)
		//panicOnError(err)
		//fmt.Println(rec)

		//		client.Set(element.id, element.value)
		//		client.Get(element.id)
		//		client.Incr("total_votes")
		//		client.Incr(element.value)
	}
}
Exemplo n.º 3
0
func runExample(client *as.Client) {
	// Write initial record.
	key, _ := as.NewKey(*shared.Namespace, *shared.Set, "opkey")
	bin1 := as.NewBin("optintbin", 7)
	bin2 := as.NewBin("optstringbin", "string value")
	log.Printf("Put: namespace=%s set=%s key=%s bin1=%s value1=%s bin2=%s value2=%s",
		key.Namespace(), key.SetName(), key.Value(), bin1.Name, bin1.Value, bin2.Name, bin2.Value)
	client.PutBins(shared.WritePolicy, key, bin1, bin2)

	// Add integer, write new string and read record.
	bin3 := as.NewBin(bin1.Name, 4)
	bin4 := as.NewBin(bin2.Name, "new string")
	log.Println("Add: ", bin3.Value)
	log.Println("Write: ", bin4.Value)
	log.Println("Read:")

	record, err := client.Operate(shared.WritePolicy, key, as.AddOp(bin3), as.PutOp(bin4), as.GetOp())
	shared.PanicOnError(err)

	if record == nil {
		log.Fatalf(
			"Failed to get: namespace=%s set=%s key=%s",
			key.Namespace(), key.SetName(), key.Value())
	}

	binExpected := as.NewBin(bin3.Name, 11)
	shared.ValidateBin(key, binExpected, record)
	shared.ValidateBin(key, bin4, record)
}
Exemplo n.º 4
0
// Increment a bin, being used as a sequence generator.
func nextSeq(seq string) (int, error) {

	keyId := fmt.Sprintf("%s:%s", SEQUENCES, seq)
	key, err := as.NewKey(NAMESPACE, SEQUENCES, keyId)
	if err != nil {
		return 0, err
	}

	rec, err := db.Operate(
		writePolicy,
		key,
		as.AddOp(as.NewBin("seq", 1)),
		as.GetOpForBin("seq"),
	)

	if err != nil {
		return 0, err
	}

	if seq, exists := rec.Bins["seq"]; !exists || int(seq.(int)) <= 0 {
		return 0, fmt.Errorf("sequence not found: %s", seq)
	}

	return rec.Bins["seq"].(int), nil
}
Exemplo n.º 5
0
func runExample(client *as.Client) {
	key, err := as.NewKey(*shared.Namespace, *shared.Set, "addkey")
	shared.PanicOnError(err)

	binName := "addbin"

	// Delete record if it already exists.
	client.Delete(shared.WritePolicy, key)

	// Perform some adds and check results.
	bin := as.NewBin(binName, 10)
	log.Println("Initial add will create record.  Initial value is ", bin.Value, ".")
	client.AddBins(shared.WritePolicy, key, bin)

	bin = as.NewBin(binName, 5)
	log.Println("Add ", bin.Value, " to existing record.")
	client.AddBins(shared.WritePolicy, key, bin)

	record, err := client.Get(shared.Policy, key, bin.Name)
	shared.PanicOnError(err)

	if record == nil {
		log.Fatalf(
			"Failed to get: namespace=%s set=%s key=%s",
			key.Namespace(), key.SetName(), key.Value())
	}

	// The value received from the server is an unsigned byte stream.
	// Convert to an integer before comparing with expected.
	received := record.Bins[bin.Name]
	expected := 15

	if received == expected {
		log.Printf("Add successful: ns=%s set=%s key=%s bin=%s value=%s",
			key.Namespace(), key.SetName(), key.Value(), bin.Name, received)
	} else {
		log.Fatalf("Add mismatch: Expected %d. Received %d.", expected, received)
	}

	// Demonstrate add and get combined.
	bin = as.NewBin(binName, 30)
	log.Println("Add ", bin.Value, " to existing record.")
	record, err = client.Operate(shared.WritePolicy, key, as.AddOp(bin), as.GetOp())
	shared.PanicOnError(err)

	expected = 45
	received = record.Bins[bin.Name]

	if received == expected {
		log.Printf("Add successful: ns=%s set=%s key=%s bin=%s value=%s",
			key.Namespace(), key.SetName(), key.Value(), bin.Name, received)
	} else {
		log.Fatalf("Add mismatch: Expected %d. Received %d.", expected, received)
	}
}
Exemplo n.º 6
0
// NewServiceCodeVersion generates a version number of the code and returns it.
func NewServiceCodeVersion(
	as *aerospike.Client, env string, service string) (
	newVersion int64, err error) {
	key, err := serviceKey(env, service)
	if err != nil {
		return 0, err
	}

	bin := aerospike.NewBin("NextVer", 1)
	record, err := as.Operate(
		nil, key, aerospike.AddOp(bin),
		aerospike.GetOpForBin("NextVer"))
	if err != nil {
		return 0, err
	}

	return int64(record.Bins["NextVer"].(int)), nil
}
Exemplo n.º 7
0
// Offer a Parcel of Stock for Sale
func (command *Command) Offer(r *http.Request, offer *m.Offer, offerId *int) error {

	var err error

	*offerId = 0

	// Check if the broker has enough inventory
	brokerKeyId := fmt.Sprintf("%s:%d", BROKERS, offer.BrokerId)
	brokerKey, err := as.NewKey(NAMESPACE, BROKERS, brokerKeyId)
	if err != nil {
		return err
	}

	brokerRec, err := db.Get(readPolicy, brokerKey, offer.Ticker, offer.Ticker+"_os")
	if err != nil {
		return err
	}

	if brokerRec == nil {
		return fmt.Errorf("Broker not found %d", offer.BrokerId)
	}

	// fmt.Printf("%#v\n\n", brokerRec)

	if brokerRec.Bins == nil || len(brokerRec.Bins) == 0 {
		return errors.New("Broker does not have any inventory of the stock")
	} else if _, exists := brokerRec.Bins[offer.Ticker+"_os"]; !exists {
		// set the outstanding as much as the inventory - bin quantity
		err := db.Put(writePolicy, brokerKey, as.BinMap{offer.Ticker + "_os": int(int(brokerRec.Bins[offer.Ticker].(int)) - offer.Quantity)})
		if err != nil {
			return err
		}
	} else {
		opRec, err := db.Operate(
			writePolicy,
			brokerKey,
			as.AddOp(as.NewBin(offer.Ticker+"_os", -1*int(offer.Quantity))),
			as.GetOp(),
		)
		if err != nil {
			return err
		}

		if inventory, exists := opRec.Bins[offer.Ticker+"_os"]; !exists || int(inventory.(int)) < offer.Quantity {
			db.Add(writePolicy, brokerKey, as.BinMap{offer.Ticker + "_os": offer.Quantity})
			return errors.New("Not enough inventory")
		}
	}

	// offer.Id = int(atomic.AddInt64(&offerIdSeq, 1))
	offer.Id, err = nextSeq("offer")
	if err != nil {
		return nil
	}

	// put the offer up
	offerKeyId := fmt.Sprintf("%s:%d", OFFERS, offer.Id)
	offerKey, err := as.NewKey(NAMESPACE, OFFERS, offerKeyId)
	if err != nil {
		return err
	}

	offerBins := as.BinMap{
		"offer_id":  offer.Id,
		"broker_id": offer.BrokerId,
		"ticker":    offer.Ticker,
		"quantity":  offer.Quantity,
		"price":     offer.Price,
		"ttl":       offer.TTL,
	}

	if err = db.Put(writePolicy, offerKey, offerBins); err != nil {
		return err
	}

	*offerId = offer.Id

	broadcast <- &m.Notification{
		Version: "2.0",
		Method:  "Offer",
		Params:  *offer,
	}

	go Auctioner(offer.Id, offer.TTL)
	return nil
}