Kite Micro-service Framework

repository·master·Indexed 25 days ago

https://github.com/koding/kite

A Go micro-service framework that functions as both an RPC server and client. Kite uses WebSockets/XHR for transport to enable bidirectional communication between Go services and web browsers. It includes the Kontrol service registry for discovery and authentication, a JavaScript library for browser integration, and the kitectl CLI tool for installing, running, and querying kite services.

Tokens
4.5K
Snippets
11
Records
40
Agent score
84%

What's inside Kite

  1. Use Kites in a web browser

    master
    Browsers can act as Kites using the kite.js library. This allows web applications to connect directly to kites via WebSocket or XHR. A connected browser kite can call methods defined on the webpage, and the kite can call browser-specific methods like log (for console logging) or alert (for user alerts).
  2. Create and run a new Kite micro-service

    master

    To write a new kite, follow these steps:

    1. Import the github.com/koding/kite package.
    2. Create a new instance using kite.New(name, version).
    3. Register method handlers using k.HandleFunc(name, handler) or k.Handle(name, handler).
    4. Configure the server (e.g., setting k.Config.Port) and call k.Run().
    package main
    
    import "github.com/koding/kite"
    
    func main() {
    	// Create a kite
    	k := kite.New("math", "1.0.0")
    
    	// Add our handler method with the name "square"
    	k.HandleFunc("square", func(r *kite.Request) (interface{}, error) {
    		a := r.Args.One().MustFloat64()
    		result := a * a    // calculate the square
    		return result, nil // send back the result
    	}).DisableAuthentication()
    
    	// Attach to a server with port 3636 and run it
    	k.Config.Port = 3636
    	k.Run()
    }
  3. Install and configure Kontrol service registry

    master

    Kontrol is the service registry and authentication service for Kites. To set it up:

    1. Install the Kontrol package: go get github.com/koding/kite/kontrol/kontrol

    2. Generate RSA keys for authentication:

      openssl genrsa -out key.pem 2048
      openssl rsa -in key.pem -pubout > key_pub.pem
    3. Set the following environment variables:

      • KONTROL_PORT: Port for Kontrol (e.g., 6000)
      • KONTROL_USERNAME: Username for the service
      • KONTROL_STORAGE: Storage backend (e.g., etcd)
      • KONTROL_KONTROLURL: The URL of the Kontrol service
      • KONTROL_PUBLICKEYFILE: Path to the public key
      • KONTROL_PRIVATEKEYFILE: Path to the private key
    4. Initialize Kontrol: ./bin/kontrol -initial

  4. Call methods on a remote Kite client

    master

    To communicate with a running kite, create a client instance using k.NewClient(url), establish the connection with Dial(), and invoke methods using Tell(methodName, args...).

    package main
    
    import (
    	"fmt"
    
    	"github.com/koding/kite"
    )
    
    func main() {
    	k := kite.New("exp2", "1.0.0")
    
    	// Connect to our math kite
    	mathWorker := k.NewClient("http://localhost:3636/kite")
    	mathWorker.Dial()
    
    	response, _ := mathWorker.Tell("square", 4) // call "square" method with argument 4
    	fmt.Println("result:", response.MustFloat64())
    }
  5. Configure Kontrol via the Kontrol struct

    master

    The Kontrol struct defines the configuration schema for the Kontrol service discovery service. It is used by multiconfig to load settings from various sources. Key configuration fields include:

    • Ip (string): The IP address for the service.
    • Port (int): The port for the service.
    • TLSCertFile (string): Path to the TLS certificate file.
    • TLSKeyFile (string): Path to the TLS key file.
    • RegisterUrl (string): The URL used for registration.
    • Initial (bool): If true, triggers the initialKey process.
    • Username (string): The username for the service.
    • KontrolURL (string): The URL of the Kontrol service.
    • PublicKeyFile (string): Path to the public key file.
    • PrivateKeyFile (string): Path to the private key file.
    • Machines ([]string): A list of machine addresses (used for etcd storage).
    • Version (string): The version of the service (defaults to 0.0.1).
    • Postgres (struct): Database configuration containing Host, Port, Username, Password, DBName, and ConnectTimeout.
    type Kontrol struct {
    	Ip          string
    	Port        int
    	TLSCertFile string
    	TLSKeyFile  string
    	RegisterUrl string
    	Initial    bool
    	Username   string
    	KontrolURL string
    	PublicKeyFile  string
    	PrivateKeyFile string
    	Machines []string
    	Version  string `default:"0.0.1"` 
    	Postgres struct {
    		Host           string `default:"localhost"` 
    		Port           int    `default:"5432"` 
    		Username       string
    		Password       string
    		DBName         string
    		ConnectTimeout int `default:"20"` 
    	}
    }
  6. Configure Client authentication with Auth

    master

    To authenticate with a remote Kite that requires credentials, set the Auth field on the Client. The Auth struct supports the following types:

    • kiteKey (uses the Key field)
    • token (uses the Key field)
    • sessionID (uses the Key field)
  7. Configure Client concurrency settings

    master

    The Client allows fine-tuning how messages are processed:

    • Concurrent (bool): If true (default), incoming messages are processed in separate goroutines. If false, they are processed sequentially.
    • ConcurrentCallbacks (bool): If true, execution of callbacks in incoming messages is concurrent. Note that this means no order is guaranteed for callback execution.
  8. Kontrol Query Path Format

    master

    When querying Kontrol for service discovery, the query path follows this structure:

    /<username>/<environment>/<name>/<version>/<region>/<hostname>/<id>

    Requirements:

    • You must provide at least the username.
    • Fields are ordered from general to specific.
    • Empty parts between fields are not allowed.
  9. Retrieve the server port

    master

    The Port() method returns the TCP port number the Kite is listening on.

    Note: This method must be called after the listener has been initialized. Because Run() is blocking, you should run it in a goroutine and use ServerReadyNotify() to wait for the listener to be ready before calling Port().

    k := kite.New("x", "1.0.0")
    go k.Run()
    <-k.ServerReadyNotify()
    port := k.Port()
  10. Make method calls with timeouts

    master
    Both TellWithTimeout and GoWithTimeout allow you to specify a time.Duration after which the call will fail if no response is received. If the timeout is 0, the behavior is identical to Tell() or Go() respectively.
  11. Initialize a new Client with NewClient()

    master

    To create a client for communicating with a remote Kite, use the NewClient method on an existing *Kite instance. The returned *Client is not connected immediately; you must call Dial(), DialTimeout(), or DialForever() to establish a connection.

    Note that if Config is not provided to the client, it will default to the configuration of the LocalKite used to create it.