Categorygithub.com/helloworlddan/run
modulepackage
0.6.11
Repository: https://github.com/helloworlddan/run.git
Documentation: pkg.go.dev

# README

Run

Package Run provides useful, yet opinionated integrations for workloads running on Cloud Run. It loosely follows the general development tips from the official documentation.

Cloud Run Services

HTTP Services

Read more in run-examples.

package main

import (
 "context"
 "fmt"
 "net/http"

 "cloud.google.com/go/bigquery"
 "github.com/helloworlddan/run"
)

func main() {
 http.HandleFunc("/", indexHandler)

 // Store config
 run.PutConfig("some-key", "some-val")

 // Store client with lazy initialization
 var bqClient *bigquery.Client
 run.LazyClient("bigquery", func() {
  run.Debug(nil, "lazy init: bigquery")
  var err error
  ctx := context.Background()
  bqClient, err = bigquery.NewClient(ctx, run.ProjectID())
  if err != nil {
   run.Error(nil, err)
  }
  run.Client("bigquery", bqClient)
 })

 // Define shutdown behavior and serve HTTP
 err := run.ServeHTTP(func(ctx context.Context) {
  run.Debug(nil, "shutting down connections...")
  if bqClient != nil { // Maybe nil due to lazy loading
   bqClient.Close()
  }
  run.Debug(nil, "connections closed")
 }, nil)
 if err != nil {
  run.Fatal(nil, err)
 }
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
 fmt.Fprintf(w, "Name: %s\n", run.ServiceName())
 fmt.Fprintf(w, "Revision: %s\n", run.ServiceRevision())
 fmt.Fprintf(w, "ProjectID: %s\n", run.ProjectID())

 // Access config
 cfg, err := run.GetConfig("some-key")
 if err != nil {
  run.Error(r, err)
 }

 // Access client
 var client *bigquery.Client
 client, err = run.UseClient("bigquery", client)
 if err != nil {
  run.Error(nil, err)
 }
 // NOTE: use client
 _ = client

 fmt.Fprintf(w, "Config[some-key]: %s\n", cfg)
 run.Debugf(r, "request completed")
}

GRPC Services

Read more in run-examples.

package main

import (
 "context"
 "time"

 "github.com/helloworlddan/run"
 "github.com/helloworlddan/run-examples/run-grpc-service/runclock"
 "google.golang.org/grpc"
)

func main() {
 server := grpc.NewServer()
 runclock.RegisterRunClockServer(server, clockServer{})

 err := run.ServeGRPC(func(ctx context.Context) {
  run.Debug(nil, "shutting down connections...")
  time.Sleep(time.Second * 1) // Pretending to clean up
  run.Debug(nil, "connections closed")
 }, server)
 if err != nil {
  run.Fatal(nil, err)
 }
}

type clockServer struct {
 runclock.UnimplementedRunClockServer
}

func (srv clockServer) GetTime(ctx context.Context, in *runclock.Empty) (*runclock.Time, error) {
 now := time.Now()
 run.Debug(nil, "received request")
 return &runclock.Time{
  Formatted: now.GoString(),
 }, nil
}

A client implementation can be found here.

Cloud Run Jobs

Read more in run-examples.

package main

import (
 "context"
 "net/http"

 "cloud.google.com/go/bigquery"
 "github.com/helloworlddan/run"
)

func main() {
 // Store config
 run.PutConfig("my.app.key", "some value")
 cfgVal, err := run.GetConfig("my.app.key")
 if err != nil {
  run.Debugf(nil, "unable to read config: %v", err)
 }
 run.Infof(nil, "loaded config: %s", cfgVal)

 // Store client
 ctx := context.Background()
 bqClient, err := bigquery.NewClient(ctx, run.ProjectID())
 if err != nil {
  run.Error(nil, err)
 }
 run.Client("bigquery", bqClient)
 defer bqClient.Close()

 // Later usage
 var bqClient2 *bigquery.Client
 bqClient2, err = run.UseClient("bigquery", bqClient2)
 if err != nil {
  run.Error(nil, err)
 }

 _ = bqClient2

 // Make service account authenticated requests
 req, err := http.NewRequest(http.MethodGet, "https://google.com", nil)
 if err != nil {
  run.Error(nil, err)
 }
 req = run.AddOAuth2Header(req)
 resp, err := http.DefaultClient.Do(req)
 if err != nil {
  run.Error(nil, err)
 }
 defer resp.Body.Close()
 // read response
}

# Functions

AddOAuth2Header injects an `Authorization` header with a valid access token for the configured service account into the supplied HTTP request and returns it.
AddOIDCHeader injects an `Authorization` header with a valid identity token for the configured service account into the supplied HTTP request and returns it.
Alert logs a message with ALERT severity.
Alertf logs a message with ALERT severity and message interpolation/formatting.
Client registers an already initialized client.
CountClients returns number of stored clients.
CountConfig returns number of stored config elements.
Critical logs a message with CRITICAL severity.
Criticalf logs a message with CRITICAL severity and message interpolation/formatting.
Debug logs a message with DEBUG severity.
Debugf logs a message with DEBUG severity and message interpolation/formatting.
Default logs a message with DEFAULT severity.
Defaultf logs a message with DEFAULT severity and message interpolation/formatting.
Emergency logs a message with EMERGENCY severity.
Emergencyf logs a message with EMERGENCY severity and message interpolation/formatting.
Error logs a message with ERROR severity.
Fatal logs a message and terminates the process.
GetConfig retrieves a value for a key from the global config store.
ID returns the unique instance ID of the Cloud Run instance serving the running job or service by referring to the metadata server.
Info logs a message with INFO severity.
Infof logs a message with INFO severity and message interpolation/formatting.
JobExecution returns the execution identifier of the currently running Cloud Run job by looking up the `CLOUD_RUN_EXECUTION` environment variable.
JobName returns the name of the currently running Cloud Run job by looking up the `CLOUD_RUN_JOB` environment variable.
JobTaskAttempt looks up and returns the current task attempt for the running Cloud Run job.
JobTaskCount looks up and returns the current task count for the running Cloud Run job.
JobTaskIndex looks up and returns the current task index for the running Cloud Run job.
KNativeService loads and returns a KNative Serving representation of the current service.
LazyClient registers an uninitialized client name with an initialization function.
ListClientNames returns a list of all available keys store in the global clients store.
ListConfigKeys returns a list of all currently available keys in the global config store.
LoadAllConfig loads all available environment variables and puts it in the config store.
LoadConfig lookups the named environment variable, puts it's value into the global config store and returns the value.
Log logs a message.
Logf logs a message with message interpolation/formatting.
Name returns a preferred name for the currently running Cloud Run service or job.
Notice logs a message with NOTICE severity.
Noticef logs a message with NOTICE severity and message interpolation/formatting.
ProjectID attempts to resolve the alphanumeric Google Cloud project ID that is hosting the current Cloud Run instance.
ProjectNumber looks up the numeric project number of the current Google Cloud project hosting the Cloud Run instance.
PutConfig adds a K/V pair to the global config store.
Region looks up the actively serving region for this Cloud Run service.
ResetClients deletes all previously configured clients.
ResetConfig deletes all previously configured config.
ResetInstance resets the cached metadata of this instance.
ServeGRPC starts the GRPC server, listens and serves requests It also traps SIGINT and SIGTERM.
ServeHTTP starts the HTTP server, listens and serves requests It also traps SIGINT and SIGTERM.
ServiceAccountAccessToken looks up and returns a fresh OAuth2 access token for the service account configured for this Cloud Run instance.
ServiceAccountEmail looks up and returns the email of the service account configured for this Cloud Run instance.
ServiceAccountIdentityToken attempts to mint an OIDC Identity Token for the specified `audience` using the metadata server.
ServiceName returns the name of the currently running Cloud Run service by looking up the `K_SERVICE` environment variable.
ServicePort looks up and returns the configured service `$PORT` for this Cloud Run service.
ServiceRevision returns the revision identifier of the currently running Cloud Run service by looking up the `K_REVISION` environment variable.
URL infers the URL with which this service will be addressable.
UseClient is intended to retrieve a pointer to a client for a given key name.
Warning logs a message with WARNING severity.
Warningf logs a message with WARNING severity and message interpolation/formatting.

# Structs

LogEntry is the structured version of a single log entry intended to be stored in Google Cloud Logging in JSON-serialized form.
SourceLocation is the structured version of a location in the source code (at compile time) which emits a log entry (at runtime).