Git Product home page Git Product logo

base's Introduction

moov-io/base

GoDoc Build Status Go Report Card Apbasee 2 licensed

Package github.com/moov-io/base implements core libraries used in multiple Moov projects. Refer to each projects documentation for more details.

Getting Started

You can either clone down the code (git clone [email protected]:moov-io/base.git) or grab the modules into your cache (go get -u github.com/moov-io/base).

Configuration

Environmental Variable Description Default
KUBERNETES_SERVICE_ACCOUNT_FILEPATH Filepath to Kubernetes service account /var/run/secrets/kubernetes.io

Getting Help

channel info
Twitter @moov You can follow Moov.io's Twitter feed to get updates on our project(s). You can also tweet us questions or just share blogs or stories.
GitHub Issue If you are able to reproduce a problem please open a GitHub Issue under the specific project that caused the error.
moov-io slack Join our slack channel to have an interactive discussion about the development of the project.

Supported and Tested Platforms

  • 64-bit Linux (Ubuntu, Debian), macOS, and Windows

Contributing

Yes please! Please review our Contributing guide and Code of Conduct to get started!

This project uses Go Modules and uses Go 1.14 or higher. See Golang's install instructions for help setting up Go. You can download the source code and we offer tagged and released versions as well. We highly recommend you use a tagged release for production.

License

Apbasee License 2.0 See LICENSE for details.

base's People

Contributors

adamdecaf avatar adelelopez avatar alexjplant avatar alovak avatar ashton-herrington avatar atonks2 avatar bkmoovio avatar darwinz avatar dependabot[bot] avatar gyao852 avatar hampgoodwin avatar infernojj avatar johnjbecker avatar joshleckbee avatar kolaworld avatar mhargrove avatar michaelabbott25 avatar mvienneau avatar nean avatar nlakritz avatar pa3ng avatar renovate-bot avatar renovate[bot] avatar sarumont avatar snyk-bot avatar thefong avatar vxio avatar wadearnold avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

base's Issues

http: base setup for Moov HTTP servers

We're starting to see a fair amount of drift between http.Server's used in Moov. This is intentional as overtime we've adapted servers, but we should consolidate somewhat. There's a lot of re-used features that should be in a common library.

  • X-Request-Id / X-Idempotency-Key / X-User-Id extraction
  • GET /ping route
  • 4xx / 5xx error encoding, logging, etc
    • We can use runtime.Caller(n) here too.
  • Metrics and Log timing (via http.ResponseWriter)
  • CORS headers

log: add timestamp key-value to all logs

We should add a timestamp to all logs using

logger = log.With(logger, "ts", log.DefaultTimestampUTC)

logger.Log("msg", "hello")

// Output:
// ts=2016-01-01T12:34:56Z msg=hello

Split migrations by environment (prod, staging, etc.)

The database package currently supports running a different set of migrations based on the database specified in the config (sqlite or mysql currently). We should support something similar, but have one set of migrations for prod and another set for staging. You can see the sqlite vs mysql migrations at work here:

func RunMigrations(logger log.Logger, config DatabaseConfig) error {

Can't use InMemory SQLite

PayGate Version: ``

What were you trying to do?

use database.InMemorySqliteConfig with database.NewAndMigrate

What did you expect to see?

connection to database created and database migrated

What did you see?

err:"no such table: items"

ID() should be more unique

The existing implementation of ID() string only creates random hex strings. There's nothing to ensure uniqueness. We should migrate to something which does.

Currently our stack cares these strings are 40 characters long and of hex strings to strip them from Prometheus paths. (e.g. GET /users/fffffffffffffff/accounts to get-users-accounts)

Candidates

sqlite: create helpers for migration, connections, testing

We've got a fairly good sqlite setup working for our apps and consolidating that would help keep apps uniform. I'm proposing a few new packages.

github.com/moov-io/base/database

// migrate runs our database migrations (defined at the top of this file)
// over a sqlite database it creates first.
// To configure where on disk the sqlite db is set SQLITE_DB_PATH.
//
// You use db like any other database/sql driver.
//
// https://github.com/mattn/go-sqlite3/blob/master/_example/simple/simple.go
// https://astaxie.gitbooks.io/build-web-application-with-golang/en/05.3.html
func Migrate(db *sql.DB, logger log.Logger) error {
	logger.Log("sqlite", "starting sqlite migrations...")
	for i := range migrations {
		row := migrations[i]
		res, err := db.Exec(row)
		if err != nil {
			return fmt.Errorf("migration #%d [%s...] had problem: %v", i, row[:40], err)
		}
		n, err := res.RowsAffected()
		if err == nil {
			logger.Log("sqlite", fmt.Sprintf("migration #%d [%s...] changed %d rows", i, row[:40], n))
		}
	}
	logger.Log("sqlite", "finished migrations")
	return nil
}

Perhaps one day we'll adopt flyway or a version table. For now this works.

github.com/moov-io/base/database/sqlite

func DBPath() string {
	path := os.Getenv("SQLITE_DB_PATH")
	if path == "" || strings.Contains(path, "..") {
		// set default if empty or trying to escape
		// don't filepath.ABS to avoid full-fs reads
		path = "paygate.db"
	}
	return path
}

func Connection(path string) (*sql.DB, error) {
	db, err := sql.Open("sqlite3", path)
	if err != nil {
		err = fmt.Errorf("problem opening sqlite3 file: %v", err)
		logger.Log("sqlite", err)
		return nil, err
	}
	return db, nil
}

func Version() string {
	sqliteVersion, _, _ := sqlite3.Version()
	return sqliteVersion	
}

github.com/moov-io/base/database/sqlite/testsqlite

type TestSqliteDB struct {
	db *sql.DB
	dir string // temp dir created for sqlite files
}

func (r *TestSqliteDB) Close() error {
	if err := r.db.Close(); err != nil {
		return err
	}
	return os.RemoveAll(r.dir)
}

// Connection returns a TestSqliteDB which can be used in tests
// as a clean sqlite database. All migrations are ran on the db before.
//
// Callers should call close on the returned *TestSqliteDB.
func Connection(migrator func (db *sql.DB, logger log.Logger) error) (*TestSqliteDB, error) {
	dir, err := ioutil.TempDir("", "test-sqlite")
	if err != nil {
		return nil, err
	}

	db, err := createSqliteConnection(filepath.Join(dir, "database.db"))
	if err != nil {
		return nil, err
	}

	logger := log.NewLogfmtLogger(ioutil.Discard)
	if err := migrator(db, logger); err != nil {
		return nil, err
	}
	return &TestSqliteDB{db, dir}, nil
}

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

docker-compose
docker-compose.yml
  • mysql 9-oracle
dockerfile
mysql/Dockerfile
  • mysql 9.0-oracle
github-actions
.github/workflows/cgo.yml
  • actions/setup-go v5
  • actions/checkout v4
.github/workflows/codeql.yaml
  • actions/checkout v4
  • github/codeql-action v3
  • github/codeql-action v3
.github/workflows/mysql-volumeless.yml
  • actions/checkout v4
.github/workflows/nocgo.yml
  • actions/setup-go v5
  • actions/checkout v4
gomod
go.mod
  • go 1.21
  • cloud.google.com/go/spanner v1.67.0
  • github.com/go-kit/kit v0.13.0
  • github.com/go-kit/log v0.2.1
  • github.com/go-sql-driver/mysql v1.8.1
  • github.com/golang-migrate/migrate/v4 v4.17.1
  • github.com/google/uuid v1.6.0
  • github.com/googleapis/gax-go/v2 v2.13.0
  • github.com/googleapis/go-sql-spanner v1.7.1
  • github.com/gorilla/mux v1.8.1
  • github.com/madflojo/testcerts v1.2.0
  • github.com/markbates/pkger v0.17.1
  • github.com/mitchellh/mapstructure v1.5.0
  • github.com/prometheus/client_golang v1.20.2
  • github.com/rickar/cal/v2 v2.1.18
  • github.com/spf13/viper v1.19.0
  • github.com/stretchr/testify v1.9.0
  • go.opentelemetry.io/otel v1.29.0
  • go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.29.0
  • go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.29.0
  • go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.29.0
  • go.opentelemetry.io/otel/sdk v1.29.0
  • go.opentelemetry.io/otel/trace v1.29.0
  • google.golang.org/grpc v1.66.0

  • Check this box to trigger a request for Renovate to run again on this repository

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

logging: add a method for logging string slices

We can do

logger.Set("orgIDs", log.String(fmt.Sprintf("[%s]",strings.Join(organizationIDs, ","))))

but a string array method would be helpful:

logger.Set("orgIDs", log.Strings(organizationIDs))

Both would output orgIDs=["id-1", "id-2", "id-3"]


Type signature for the valuer would be:

func Strings(vals []string) Valuer

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.