Skip to content

Commit

Permalink
refactor: added makefile help
Browse files Browse the repository at this point in the history
  • Loading branch information
geolffreym committed Apr 12, 2024
1 parent 1e16e0f commit 1f596fa
Show file tree
Hide file tree
Showing 7 changed files with 69 additions and 41 deletions.
41 changes: 33 additions & 8 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ OSX_64=${BINARY_LINUX}-${ARCH_64}
# -count 1 idiomatic no cached testing
# -race test race condition for routines
# @ = dont echo the output
.PHONY: test ## run tests
test:
@go test -v ./... -count 1 -race -covermode=atomic
@echo "[OK] test finished"
Expand All @@ -36,8 +37,9 @@ test:
# make benchmark > a.old
# make benchmark > b.new
# benchcmp a.old b.new
.PHONY: benchmark ## run benchmark tests
benchmark:
@go test ./... -bench=. -benchtime 100000x -count 5
@perflock -governor=80% go test -run=^Benchmarck$ -benchtime 1s -bench=. -count=1
@echo "[OK] benchmark finished"


Expand All @@ -54,71 +56,94 @@ benchmark:
# For fancy visualization:
# Could use Graphviz (https://graphviz.org/download/)
# eg. go tool pprof -web bin/main-linux-amd64 cpu.prof

.PHONY: profiling ## run profiling tests
profiling:
@perflock -governor=80% go test -benchmem -run=^$ -benchtime 1s -bench=. -cpu 1,2,4,8 -count=1 -memprofile mem.prof -cpup rofile cpu.prof
@perflock -governor=80% go test -run=^Benchmarck$ -benchmem -benchtime 1s -bench=. -cpu 1,2,4,8 -count=1 -memprofile mem.prof -cpuprofile cpu.prof
@echo "[OK] profiling finished"

.PHONY: coverage ## run tests coverage
coverage:
@go test -v ./... -race -covermode=atomic -coverprofile coverage ./...
@echo "[OK] coverage finished"


.PHONY: coverage-export ## run tests coverage export
coverage-export: coverage
@go tool cover -html=coverage
@echo "[OK] code test coverage finished"

# Allow to preview documentation.
# Please verify your GOPATH before run this command
.PHONY: preview-doc ## run local documentation server
preview-doc:
@godoc -http=localhost:6060 -links=true

.PHONY: build ## compiles the command into and executable
build:
@go build -v ./...

imports:
@goimport

.PHONY: format ## automatically formats Go source cod
format:
@go fmt ./...
@goimports -w .
@echo "[OK] code format finished"

.PHONY: check ## examines Go source code and reports suspicious constructs
check:
@go vet -v ./...
@echo "[OK] code check finished"

.PHONY: clean ## removes generated files and clean go cache
clean:
@go clean --cache ./...
@rm -f mem.prof
@rm -f prof.mem
@rm -rf bin
@echo "[OK] cleaned"

.PHONY: compile-win ## compiles window exec
compile-win:
@GOOS=windows GOARCH=amd64 go build -o bin/${WIN_64} ${INPUT}
@GOOS=windows GOARCH=386 go build -o bin/${WIN_32} ${INPUT}

#Go1.15 deprecates 32-bit macOS builds
# go build -x to show compilation details
#GOOS=darwin GOARCH=386 go build -o bin/main-mac-386 main.go
.PHONY: compile-mac ## compiles mac exec
compile-mac:
@GOOS=darwin GOARCH=amd64 go build -o bin/${OSX_64} ${INPUT}

.PHONY: compile-linux ## compiles linux exec
compile-linux:
@GOOS=linux GOARCH=amd64 go build -o bin/${LINUX_64} ${INPUT}
@GOOS=linux GOARCH=386 go build -o bin/${LINUX_32} ${INPUT}

.PHONY: compile ## compiles all os exec
compile: compile-linux compile-win compile-mac
@echo "[OK] Compiling for every OS and Platform"

build-gc:
@go build -gcflags='-m -m' $(filter-out $@,$(MAKECMDGOALS))

.PHONY: run ## compiles and runs the named main Go package
run:
@go run ${INPUT} $(filter-out $@,$(MAKECMDGOALS))

.PHONY: update-pkg-cache ## updated the package cache version
update-pkg-cache:
GOPROXY=https://proxy.golang.org GO111MODULE=on \
go get github.com/${USER}/${PACKAGE}@v${VERSION}

# https://go.dev/ref/mod#go-mod-vendor
.PHONY: vendorize ## lock dependencies
vendorize:
@go mod vendor
@echo "[OK]"

all: build test check-test-coverage code-check compile
all: build test check-test-coverage code-check compile

.PHONY: help ## display this message
help:
@grep -E \
'^.PHONY: .*?## .*$$' $(MAKEFILE_LIST) | \
sort | \
awk 'BEGIN {FS = ".PHONY: |## "}; {printf "\033[36m%-19s\033[0m %s\n", $$2, $$3}'
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,12 +107,12 @@ Some available capabilities for dev support:
* **Test Coverage**: `make coverage`
* **Benchmark**: `make benchmark`
* **Profiling**: `make profiling`
* **Code check**: `make code-check`
* **Code format**: `make code-fmt`
* **Code check**: `make check`
* **Code format**: `make format`
* **Flush cache**: `make clean`
* **Build**: `make build`

Note: Please check [Makefile](https://github.com/geolffreym/p2p-noise/Makefile) for more capabilities.
Note: Run `make help` to check for more capabilities.

## More info

Expand Down
46 changes: 26 additions & 20 deletions node.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Noise based P2P Library.
// Please read more about [Noise Protocol].
// Package noise implements the Noise Protocol for peer-to-peer communication.
// For more information about the Noise Protocol, please visit: [Noise Protocol].
//
// [Noise Protocol]: http://www.noiseprotocol.org/noise.html
package noise
Expand All @@ -14,7 +14,7 @@ import (
"github.com/oxtoacart/bpool"
)

// futureDeadline calculate a new time for deadline since now.
// futureDeadline calculate and return a new time for deadline since now.
func futureDeadLine(deadline time.Duration) time.Time {
if deadline == 0 {
// deadline 0 = no deadline
Expand Down Expand Up @@ -45,6 +45,8 @@ type Config interface {
KeepAlive() time.Duration
}

// Node represents a network node capable of handling connections,
// routing messages, and managing configurations.
type Node struct {
// Bound local network listener.
listener net.Listener
Expand Down Expand Up @@ -74,8 +76,9 @@ func New(config Config) *Node {
}
}

// Signals proxy channels to subscriber.
// The listening routine should be stopped using returned cancel func.
// Signals initiates the signaling process to proxy channels to subscribers.
// It returns a channel of type Signal to intercept events and a cancel function to stop the listening routine.
// The channel is closed during the cancellation of listening.
func (n *Node) Signals() (<-chan Signal, context.CancelFunc) {
ctx, cancel := context.WithCancel(context.Background())
// this channel is closed during listening cancellation
Expand All @@ -95,9 +98,10 @@ func (n *Node) Disconnect() {
}
}

// Send emit a new message using peer id.
// If peer id doesn't exists or peer is not connected return error.
// Calling Send extends write deadline.
// Send emits a new message using a peer ID.
// It returns the total bytes sent if there is no error; otherwise, it returns 0.
// If the peer ID doesn't exist or the peer is not connected, it returns an error.
// Calling Send extends the write deadline.
func (n *Node) Send(rawID string, message []byte) (uint32, error) {
id := newIDFromString(rawID)
// Check if id exists in connected peers
Expand All @@ -116,9 +120,9 @@ func (n *Node) Send(rawID string, message []byte) (uint32, error) {
return bytes, err
}

// watch keep running waiting for incoming messages.
// After every new message the connection is verified, if local connection is closed or remote peer is disconnected the routine is stopped.
// Incoming message monitor is suggested to be processed in go routines.
// watch keeps running, waiting for incoming messages.
// After receiving each new message, the connection is verified. If the local connection is closed or the remote peer is disconnected, the routine stops.
// It is suggested to process incoming messages in separate goroutines.
func (n *Node) watch(peer *peer) {

KEEPALIVE:
Expand Down Expand Up @@ -154,7 +158,9 @@ KEEPALIVE:

}

// setupTCPConnection configure TCP connection behavior.
// setupTCPConnection configures the behavior of a TCP connection.
// It takes a net.TCPConn connection and modifies its settings according to the Node configuration.
// If any of the configurations cannot be fulfilled, it returns an error.
func (n *Node) setupTCPConnection(conn *net.TCPConn) error {
// If tcp enforce keep alive connection.
// SetKeepAlive sets whether the operating system should send keep-alive messages on the connection.
Expand All @@ -172,10 +178,10 @@ func (n *Node) setupTCPConnection(conn *net.TCPConn) error {
return nil
}

// handshake starts a new handshake for incoming or dialed connection.
// After handshake completes a new session is created and a new peer is created to be added to router.
// If TCP protocol is used connection is enforced to keep alive.
// Return err if max peers connected exceed MaxPeerConnected otherwise return nil.
// handshake initiates a new handshake for an incoming or dialed connection.
// After the handshake completes, a new session is created, and a new peer is added to the router.
// If the TCP protocol is used, the connection is enforced to keep alive.
// Returns an error if the maximum number of connected peers exceeds MaxPeersConnected; otherwise, returns nil.
func (n *Node) handshake(conn net.Conn, initialize bool) error {

// Assertion for tcp connection to keep alive
Expand Down Expand Up @@ -223,8 +229,8 @@ func (n *Node) handshake(conn net.Conn, initialize bool) error {
return nil
}

// routing initialize route in routing table from session.
// Return the recent added peer.
// routing initializes a route in the routing table from a session.
// It returns the recently added peer.
func (n *Node) routing(conn *session) *peer {
// Initial deadline for connection.
// A deadline is an absolute time after which I/O operations
Expand Down Expand Up @@ -308,8 +314,8 @@ func (n *Node) Close() error {
return nil
}

// Dial attempt to connect to remote node and add connected peer to routing table.
// Return error if error occurred while dialing node.
// Dial attempts to connect to a remote node and adds the connected peer to the routing table.
// It returns an error if an error occurred while dialing the node.
func (n *Node) Dial(addr string) error {
protocol := n.config.Protocol() // eg. tcp
timeout := n.config.DialTimeout() // max time waiting for dial.
Expand Down
4 changes: 1 addition & 3 deletions node_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -247,9 +247,7 @@ func TestSomeNodesHandshake(t *testing.T) {

}

// go test -benchmem -run=^$ -benchmem -memprofile memprofile.out -cpuprofile cpuprofile.out -bench=BenchmarkHandshakeProfile
// go tool pprof {file}
func BenchmarkHandshakeProfile(b *testing.B) {
func BenchmarkHandshake(b *testing.B) {

// Discard logs to avoid extra allocations.
log.SetOutput(ioutil.Discard)
Expand Down
3 changes: 1 addition & 2 deletions peer.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,7 @@ func unmarshall(b []byte) packet {
return p
}

// peer its the trusty remote peer.
// Provide needed methods to interact with the secured session.
// peer represents a trusty remote peer, providing necessary methods to interact with the secured session.
type peer struct {
// Optimizing space with ordered types.
// the attributes orders matters.
Expand Down
6 changes: 3 additions & 3 deletions router.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import (
"sync/atomic"
)

// router keep a hash table to associate ID with peer.
// It implements a unstructured mesh topology.
// router keeps a hash table to associate IDs with peers.
// It implements an unstructured mesh topology.
// Unstructured P2P topologies do not attempt to organize all peers into a single, structured topology.
// Rather, each peer attempts to keep a "sensible" set of other peers in its routing table
// Rather, each peer attempts to keep a "sensible" set of other peers in its routing table.
type router struct {
sync.Map // embed map
counter uint32
Expand Down
4 changes: 2 additions & 2 deletions subscriber.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ package noise

import "context"

// subscriber intercept Signal from already subscribed topics in broker
// Handle actions to emit or receive events.
// subscriber intercept Signal from already subscribed topics in broker.
// It handles actions to emit or receive events.
type subscriber struct {
// No, you don't need to close the channel
// https://stackoverflow.com/questions/8593645/is-it-ok-to-leave-a-channel-open
Expand Down

0 comments on commit 1f596fa

Please sign in to comment.