bank

package
v0.23.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 10, 2024 License: Apache-2.0 Imports: 8 Imported by: 0

Documentation

Overview

Package bank includes an example of how to test Service Weaver applications using the sim package.

The example involves a bank that incorrectly implements withdrawals. Specifically, the withdrawal operation (1) reads a user's bank account balance to determine if there are sufficient funds for the withdrawal and then (2) performs the actual withdrawal. However, steps (1) and (2) are not performed atomically. This lack of atomicity allows two withdrawals to race, producing a bank account with a negative balance.

For example, consider a bank account with an initial balance of $100 and two operations both racing to withdraw $100. The following execution is possible.

  • Withdraw 1 sees a balance of $100.
  • Withdraw 2 sees a balance of $100.
  • Withdraw 2 withdraws, leaving a balance of $0.
  • Withdraw 1 withdraws, leaving a balance of -$100.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Bank

type Bank interface {
	// Deposit adds the provided amount to the provided user's bank account
	// balance and returns the balance after the deposit.
	//
	// Deposit returns an error if the provided amount is negative.
	Deposit(ctx context.Context, user string, amount int) (int, error)

	// Withdraw subtracts the provided amount from the provided user's bank
	// account balance and returns the balance after the withdrawal.
	//
	// Withdraw returns an error if the provided amount is negative or if the
	// user's balance is less than the withdrawal amount.
	Withdraw(ctx context.Context, user string, amount int) (int, error)
}

A Bank is a persistent collection of user bank account balances.

type Store

type Store interface {
	// Get gets the value of the provided key.
	Get(ctx context.Context, key string) (int, error)

	// Add atomically adds the provided delta to the provided key and returns
	// the resulting sum. Note that delta can be positive or negative. For
	// example, Add(ctx, "foo", 10) adds 10 to "foo", while Add(ctx, "foo",
	// -10) subtracts 10 from "foo".
	Add(ctx context.Context, key string, delta int) (int, error)
}

A Store is a persistent map from strings to integers, like a map[string]int.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL