sourcegraph/lib/managedservicesplatform/runtime/sanitycheck.go
Robert Lin 141bd58057
msp/runtime: export contract and helpers for direct usage (#61488)
Exports package `github.com/sourcegraph/sourcegraph/lib/managedservicesplatform/runtime/contract` to expose previously-internal env-configuration (the "MSP contract") loading, helpers, and configuration. This allows programs that aren't 100% in the MSP runtime ecosystem yet (hopefully reducing future barrier to entry), or are in particular scenarios where they might not want to use runtime ([e.g. MSP jobs which doesn't have proper runtime support yet](https://sourcegraph.slack.com/archives/C06062P5TS5/p1711663052720289)), to integrate with MSP-provisioned infrastructure like BigQuery, PostgreSQL, and even Sentry etc. directly.

The recommended path will still be to build a `runtime`-compliant interface, but it can be a hassle to migrate sometimes, and as mentioned, we don't properly support jobs yet.

Simple example:

```go
	// Parse the environment into an Env instance.
	e, _ := contract.ParseEnv([]string{"MSP=true"})

	// Extract Contract instance from Env configuration.
	c := contract.New(logger, service, e)

	// Also load other custom configuration here from Env you want here

	// Check for errors on Env retrieval (missing/invalid values, etc.)
	if err := e.Validate(); err != nil { ... }

	// Use Contract helpers and configuration values
	writer, _ := c.BigQuery.GetTableWriter(ctx, "my-table")
	writer.Write(...)
```

## Test plan

There are no functionality changes, only code moving. But, ran some sanity checks:

```
sg run msp-example
sg run telemetry-gateway 
sg run pings
```

---------

Co-authored-by: Chris Smith <chrsmith@users.noreply.github.com>
2024-04-04 11:05:51 +00:00

28 lines
732 B
Go

package runtime
import (
"encoding/json"
"fmt"
"os"
"github.com/sourcegraph/sourcegraph/lib/managedservicesplatform/runtime/contract"
)
// passSanityCheck exits with a code zero if the environment variable SANITY_CHECK equals
// to "true". See internal/sanitycheck.
func passSanityCheck(svc contract.ServiceMetadataProvider) {
if os.Getenv("SANITY_CHECK") == "true" {
// dump metadata to stdout
if err := json.NewEncoder(os.Stdout).Encode(map[string]string{
"name": svc.Name(),
"version": svc.Version(),
}); err != nil {
fmt.Fprintf(os.Stderr, "Dump metadata: %s", err)
os.Exit(1)
}
// report success in stderr
fmt.Fprint(os.Stderr, "Sanity check passed, exiting without error")
os.Exit(0)
}
}