Categorygithub.com/openfresh/plasma
modulepackage
0.0.0-20190815105719-e40ef661b820
Repository: https://github.com/openfresh/plasma.git
Documentation: pkg.go.dev

# README

plasma

Circle CI Language issues License: MIT imagelayers.io Docker Stars Docker Pulls

Attention: This repository was transfererd from openfresh.

logo

plasma is event push middleware by using gRPC stream.

Description

Plasma is middleware for sending event specialized for a stream. Plasma provides EventSource and gRPC Stream from the same endpoint.

img

Installation

This middleware requires Redis.

From Source

$ git clone git://github.com/openfresh/plasma.git $GOPATH/src/github.com/openfresh/plasma
$ cd  $GOPATH/src/github.com/openfresh/plasma
$ make deps
$ make build

The binary is generated under the bin/ directory.

Using docker

You can also use the Docker image.

$ docker run -p 8080:8080 -p 50051:50051 -p 9999:9999 openfresh/plasma

Using docker-compose

You can use docker-compose for easy use without preparing Redis.

$ git clone git://github.com/openfresh/plasma.git $GOPATH/src/github.com/openfresh/plasma
$ cd  $GOPATH/src/github.com/openfresh/plasma
$ docker-compose up -d

Usage Subscriber

Server Sent Events

Using server-sent events

Your can use SSE if you request with Accept:text-stream header.

You request events that you want to subscribe to this endpoint. You can specify multiple events separated by commas. The query name can be set with the EventQuery environment variable.(default value of EventQuery is eventType ).

Here is a simple example using [Yaffle / EventSource] (https://github.com/Yaffle/EventSource).

    var source = new EventSource('//localhost:8080/?eventType=program:1234:views,program:1234:poll,program:1234:annotation');
    
    source.addEventListener("open", function(e) {
        console.log("open");
    });
    
    source.addEventListener("error", function(e) {
        console.log("error");
    });
    
    source.addEventListener("message", function(e) {
        console.log("message event: ", e.data);
    });

The JSON schema of data returned from Plasma is as follows.

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "id": "/events",
    "properties": {
        "data": {
            "id": "/events/data",
            "type": "string"
        },
        "meta": {
            "id": "/events/meta",
            "properties": {
                "type": {
                    "id": "/events/meta/type",
                    "type": "string"
                }
            },
            "type": "object"
        }
    },
    "type": "object"
}

If the DEBUG environment variable is enabled, you can access the debug endpoint.

GET /debug

You can publish events to Redis from this endpoint. You need to enter valid JSON in EventData form.

gRPC Stream

You can subscribe to events using gRPC Stream.

The ProtocolBuffer file is here .

The following is a simple Go sample.

func main() {
    conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()

    client := proto.NewStreamServiceClient(conn)
    ctx := context.Background()

    req := proto.Request{
        Events: []*proto.EventType{
            eventType("program:1234:poll"),
            eventType("program:1234:views"),
        },
    }

    ss, err := client.Events(ctx)
    if err != nil {
        log.Fatal(err)
    }

    // subscribe event
    if err := ss.Send(&req); err != nil {
        log.Fatal(err)
    }

    for {
        resp, err := ss.Recv()
        if err != nil {
            log.Println(err)
            continue
        }
        if resp == nil {
            log.Println("payload is nil")
            continue
        }
        fmt.Printf("Meta: %s\tData: %s\n", resp.EventType.Type, resp.Data)
    }
}

unsubscribe

Events request is stream. If you unsubscribe event, set empty event data.

    req := proto.Request{
        // empty events
        Events: []*proto.EventType{},
    }

    ss, err := client.Events(ctx)
    if err != nil {
        log.Fatal(err)
    }

    // unsubscribe event
    if err := ss.Send(&req); err != nil {
        log.Fatal(err)
    }

Usage Publisher

You publish events to the channel that Plasma subscribes according to the following JSON Schema.

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "id": "/events",
    "properties": {
        "data": {
            "id": "/events/data",
            "type": "string"
        },
        "meta": {
            "id": "/events/meta",
            "properties": {
                "type": {
                    "id": "/events/meta/type",
                    "type": "string"
                }
            },
            "type": "object"
        }
    },
    "type": "object"
}

openfresh/plasma-go is a library that wraps publish an event to Redis.

HealthCheck

GET /hc

You can do a health check. Check the status of Redis. If there is a problem it returns 500, and if there is no problem it returns 200.

Metrics

GET /metrics/go

You can get golang metrics from this endpoint.

The following golang metrics can be taken.

nametypedesc
go_versionstringversion of go
go_osstringos
go_archstringarch
cpu_numintnumber of cpus
goroutine_numintnumber of goroutines
gomaxprocsintnumber of operating system threads
cgo_call_numint64number of cgo calls
memory_allocuint64bytes of allocated heap objects
memory_total_allocuint64cumulative bytes allocated for heap objects
memory_sysuint64total bytes of memory
memory_lookupsuint64number of pointer
memory_mallocsuint64cumulative count of heap objects allocated
memory_freesuint64cumulative count of heap objects freed
memory_stackuint64bytes in stack spans
heap_allocuint64bytes of allocated heap objects
heap_sysuint64bytes of heap memory obtained
heap_idleuint64bytes in idle spans
heap_inuseuint64bytes in in-use spans
heap_releaseduint64bytes of physical memory returned to the OS
heap_objectsuint64number of allocated heap objects
gc_nextuint64target heap size of the next GC cycle
gc_lastuint64time the last garbage collection finished, as, nanoseconds since 1970
gc_numuint32number of completed GC cycles
gc_per_secondfloat64GC per second
gc_pause_per_secondfloat64GC pause per second
gc_pause[]float64GC pause

GET /metrics/plasma

You can get plasma metrics from this endpoint.

The following golang metrics can be taken.

nametypedesc
connectionsint64number of connected all clients
connections_sseint64number of connected SSE sclients
connections_grpcint64number of connected gRPC sclients

Config

nametypedescdefaultnote
PLASMA_PORTstringhttp(https) port number8080
PLASMA_GRPC_PORTstringgRPC port number50051
PLASMA_METRICS_PORTstringmetrics port number9999
PLASMA_PPROF_HOSTstringpprof host0.0.0.0
PLASMA_PPROF_PORTstringpprof port number6060
PLASMA_DEBUGbooldebug modefalse
PLASMA_ORIGINstringset to Access-Controll-Allow-Origin
PLASMA_SSE_RETRYintreconnect to the source milliseconds after each connection is closed2000
PLASMA_SSE_EVENTQUERYstringuse as a querystring in SSEeventTypeex) /?eventType=program:1234:views
PLASMA_SUBSCRIBER_TYPEstringsubscriber typemocksupport "mock" and "redis"
PLASMA_SUBSCRIBER_REDIS_ADDRstringRedis address including port numberlocalhost:6379
PLASMA_SUBSCRIBER_REDIS_PASSWORDstringRedis password
PLASMA_SUBSCRIBER_REDIS_DBintRedis DB0
PLASMA_SUBSCRIBER_REDIS_CHANNELSstringchannels of Redis to subscribe (multiple specifications possible)
PLASMA_SUBSCRIBER_REDIS_OVER_MAX_RETRY_BEHAVIORstringBehavior of plasma when the number of retries connecting to Redis exceeds the maximum"die" or "alive"
PLASMA_SUBSCRIBER_REDIS_TIMEOUTtime.Durationtimeout for receive message from Redis1s
PLASMA_SUBSCRIBER_REDIS_RETRY_INTERVALtime.Durationinterval for retry to receive message from Redis5s
PLASMA_ERROR_LOG_OUTstringlog file pathstdout, stderr, filepath
PLASMA_ERROR_LOG_LEVELstringlog output levelpanic,fatal,error,warn,info,debug
PLASMA_ACCESS_LOG_OUTstringlog file pathstdout, stderr, filepath
PLASMA_ACCESS_LOG_LEVELstringlog output levelpanic,fatal,error,warn,info,debug
PLASMA_TLS_CERT_FILEstringcert file pathTLS is enabled only when you set both PLASMA_TLS_CERT_FILE and PLASMA_TLS_KEY_FILE
PLASMA_TLS_KEY_FILEstringkey file path
PLASMA_METRICS_TYPEstringmetrics typesupport "log" or "syslog". if this value is empty, metrics will be disabled
PLASMA_METRICS_INTERVALtime.Durationinterval for update metrics10s
PLASMA_METRICS_LOG_OUTstringlog file pathstdout
PLASMA_METRICS_LOG_PREFIXstringlog prefixmetrics
PLASMA_METRICS_LOG_FLAGintdefine which text to prefix to each log entry generated by the Loggerlog.Lmicrosecondshttps://golang.org/pkg/log/#pkg-constants
PLASMA_METRICS_LOG_INTERVALtime.Durationinterval for send to logger1m
PLASMA_METRICS_SYSLOG_TAGstringtag for syslogplasma
PLASMA_METRICS_SYSLOG_INTERVALtime.Durationinterval for send to syslog1m
PLASMA_METRICS_SYSLOG_SEVERITYintsyslog serverity0https://golang.org/pkg/log/syslog/#Priority
PLASMA_METRICS_SYSLOG_FACILITYintsyslog facility0https://golang.org/pkg/log/syslog/#Priority
PLASMA_METRICS_SYSLOG_NETWORDKstringnetwork for syslog
PLASMA_METRICS_SYSLOG_ADDRstringaddress for syslog

License

See LICENSE.

Copyright © CyberAgent, Inc. All Rights Reserved.

# Packages

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Package proto is a generated protocol buffer package.
No description provided by the author
No description provided by the author
No description provided by the author