Compare commits
267 Commits
Author | SHA1 | Date | |
---|---|---|---|
92b125c1ce | |||
8f7eebc24f | |||
b0def96d14 | |||
927ca879b2 | |||
00450c9cc7 | |||
534bce2d20 | |||
53949be0cc | |||
d8fe2ff8b4 | |||
53b5ee2c6f | |||
dfd85cd871 | |||
52182261af | |||
1f3834e187 | |||
0354873c3a | |||
8e5e2167cd | |||
c26a7db47c | |||
74765b4c5f | |||
8bd7323af1 | |||
|
899dc8b3bc | ||
6e6c31b5dd | |||
94929878fe | |||
8ce469a09e | |||
88788776d2 | |||
e143e2b547 | |||
a36f99e30b | |||
326ee53333 | |||
1244c5bb4d | |||
4ccc8a9c85 | |||
8a2e84d489 | |||
d29363b78d | |||
734f751055 | |||
55d8a9ee20 | |||
07c93042ba | |||
b9bbfdf159 | |||
fbad257acc | |||
1829febb6e | |||
7838fa62a8 | |||
332803d8de | |||
11c868d476 | |||
38d6e482d7 | |||
07d4085201 | |||
45f30c0be3 | |||
bcaea675a7 | |||
3087ba1d73 | |||
3f5b19497c | |||
37d937d7ae | |||
7d68f2396e | |||
0854a7ea72 | |||
5eb0e56373 | |||
6af837fd25 | |||
ada59119cc | |||
8abc913b28 | |||
3247d144a8 | |||
7b2e3cc8aa | |||
8688179acd | |||
3e40bac5f4 | |||
e3fee6f8a6 | |||
15c020fac5 | |||
3bc046e5d4 | |||
542f36cfa5 | |||
8237e6a08e | |||
ecb60e4dc5 | |||
a1999ff81c | |||
d0f2bc8346 | |||
|
dd29bf457e | ||
d062c248e3 | |||
875f66d36e | |||
818a0e6356 | |||
56e02ec463 | |||
6ca851401d | |||
bd8216b397 | |||
2b13b3f128 | |||
9957380b6d | |||
e10f8c0fa0 | |||
45252fe4a6 | |||
faad082efe | |||
8ab35cbd9b | |||
ad58ab6943 | |||
0e97049e1d | |||
edb0bbf9cf | |||
|
1b01bd22a6 | ||
2fbaa26f0f | |||
35d3e4b332 | |||
|
e98a93d530 | ||
e3545532e8 | |||
09653c2fb2 | |||
70adfeab0d | |||
a45b672c98 | |||
4509323cae | |||
b3f4c670d5 | |||
778dd449e2 | |||
1d16983b67 | |||
f386bffd37 | |||
772bde7938 | |||
ea16f5f825 | |||
c2f34df493 | |||
efe215cd60 | |||
b4f332bf0d | |||
f47fbb1030 | |||
1e8e57a708 | |||
|
5d0959b0a1 | ||
fa8fb3aed7 | |||
cfd2d53a79 | |||
d306f77ffc | |||
e5b0a7e20d | |||
9a5b158b4d | |||
af8d81f3c6 | |||
5c9b3dae33 | |||
9f3957d101 | |||
8fd8bdcb39 | |||
80e3d239ab | |||
419cd486cf | |||
e64269b2a8 | |||
d18429e024 | |||
675e121049 | |||
d357fb1e0d | |||
e4673bcc50 | |||
a839f75a2f | |||
a7e6d61b95 | |||
650d167313 | |||
c6ba2a91e6 | |||
7ece08896f | |||
|
57f6f23294 | ||
09e6fa2fed | |||
10a09a5c6f | |||
b4e5d9462a | |||
96aa0b6906 | |||
f54658830d | |||
1e43122660 | |||
42800fa247 | |||
5b9c810653 | |||
c3def24bf4 | |||
0d1ef31764 | |||
d49afa230f | |||
e545eb4e13 | |||
f28b107372 | |||
c592fabe2a | |||
eb107020c7 | |||
bd4d4c363e | |||
2a548634fd | |||
598dddc476 | |||
887b48f1e7 | |||
6e55d07636 | |||
919520219c | |||
60a5e737f8 | |||
34f0b209cc | |||
ba8e1889fe | |||
dae5c57a60 | |||
ea590d57df | |||
|
9aa6969836 | ||
|
c00c705c24 | ||
|
0239f795d8 | ||
|
e69b43881d | ||
3a48a613fe | |||
86626c5922 | |||
ee11f39a2f | |||
3bdfdd8fd2 | |||
6dfdff7fd8 | |||
00a4785df3 | |||
|
bae3b0ef94 | ||
|
89b0565062 | ||
1f8b0aeb61 | |||
|
5b6f849e0a | ||
|
3b416fffde | ||
3a60103aed | |||
41837a67f8 | |||
852f19598d | |||
6537b35773 | |||
b733f1316f | |||
|
840af5574c | ||
|
56e5b7001c | ||
|
11dc6fd752 | ||
a2695d8699 | |||
618421de05 | |||
|
30baaabd9f | ||
df5bce1191 | |||
|
089d0fe4df | ||
a06f535303 | |||
|
eba586a329 | ||
|
d74a8645e8 | ||
|
5a00786192 | ||
|
b3e9941634 | ||
|
a5a5904302 | ||
|
a59832e57e | ||
0e42033e7f | |||
52d8255974 | |||
9830cb48a9 | |||
92d7ab2105 | |||
d2935ef399 | |||
ce4c96ae0a | |||
|
14026d15be | ||
|
2df0c7643e | ||
e13c2c48fd | |||
8db55d2e55 | |||
ed61cad961 | |||
040fc4548f | |||
6189a1b980 | |||
eb2a450a7b | |||
|
d2a30a5da1 | ||
65889c66f6 | |||
dcdf133d5b | |||
8742b55305 | |||
4a64ee72f7 | |||
881d7afeea | |||
8c95448535 | |||
c1dc041d8c | |||
|
25be0ac0f0 | ||
|
86f73cac4e | ||
485eda6ce9 | |||
dbbdb24631 | |||
723ceb4f32 | |||
bac9869bb3 | |||
610427445f | |||
|
c84a66c713 | ||
00eaae717b | |||
a102e95433 | |||
39f66cc86c | |||
bbbcb22565 | |||
cb70dfa664 | |||
1f0482fbd5 | |||
a862562284 | |||
c320c23913 | |||
|
ae848ba8bb | ||
|
8e264cbb3e | ||
|
54e523ab3f | ||
09973af099 | |||
3247da3dd0 | |||
b505455f7c | |||
293949f081 | |||
8d7e442b3a | |||
|
f7b5211af3 | ||
7eb6d030dc | |||
47e75c31c7 | |||
20ff5eed22 | |||
d23ca8db73 | |||
4dd28ac720 | |||
240b6016df | |||
cf2aa827e4 | |||
5596345382 | |||
67748a2132 | |||
c2333a9f35 | |||
4ec4c277b7 | |||
a11dd00174 | |||
cc7ebedf22 | |||
e5bf1448f4 | |||
f182bba6ff | |||
1f8810599b | |||
82248eb3b0 | |||
abb9937787 | |||
fd5ed64729 | |||
6751060d05 | |||
ef664607b4 | |||
62e482a14b | |||
a390ebf80f | |||
9a44960be7 | |||
c846c59b9b | |||
|
902bf6326b | ||
|
bddf3bf502 | ||
|
284131da98 | ||
927c7ea3c2 | |||
0e51a79bb6 | |||
1de9911b73 | |||
b4092c6619 | |||
024868bfd7 | |||
a0bbfd6d02 | |||
2cb6843773 | |||
87e1480077 | |||
bcd7f6a551 |
26
.github/dependabot.yml
vendored
Normal file
26
.github/dependabot.yml
vendored
Normal file
@@ -0,0 +1,26 @@
|
||||
# To get started with Dependabot version updates, you'll need to specify which
|
||||
# package ecosystems to update and where the package manifests are located.
|
||||
# Please see the documentation for all configuration options:
|
||||
# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
|
||||
|
||||
version: 2
|
||||
updates:
|
||||
|
||||
# Maintain dependencies for GitHub Actions
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
commit-message:
|
||||
prefix: "chore"
|
||||
include: "scope"
|
||||
|
||||
# Maintain dependencies for Golang
|
||||
- package-ecosystem: "gomod"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
commit-message:
|
||||
prefix: "chore"
|
||||
include: "scope"
|
||||
|
15
.github/generate.sh
vendored
15
.github/generate.sh
vendored
@@ -1,15 +0,0 @@
|
||||
#!/bin/bash -e
|
||||
|
||||
find . -type f -name '*.pb.*.go' -o -name '*.pb.go' -a ! -name 'message.pb.go' -delete
|
||||
PROTOS=$(find . -type f -name '*.proto' | grep -v proto/google/api)
|
||||
|
||||
mkdir -p proto/google/api
|
||||
curl -s -o proto/google/api/annotations.proto -L https://raw.githubusercontent.com/googleapis/googleapis/master/google/api/annotations.proto
|
||||
curl -s -o proto/google/api/http.proto -L https://raw.githubusercontent.com/googleapis/googleapis/master/google/api/http.proto
|
||||
|
||||
for PROTO in $PROTOS; do
|
||||
echo $PROTO
|
||||
protoc -I./proto -I. -I$(dirname $PROTO) --go-grpc_out=paths=source_relative:. --go_out=paths=source_relative:. --micro_out=paths=source_relative:. $PROTO
|
||||
done
|
||||
|
||||
rm -r proto
|
13
.github/stale.sh
vendored
13
.github/stale.sh
vendored
@@ -1,13 +0,0 @@
|
||||
#!/bin/bash -ex
|
||||
|
||||
export PATH=$PATH:$(pwd)/bin
|
||||
export GO111MODULE=on
|
||||
export GOBIN=$(pwd)/bin
|
||||
|
||||
#go get github.com/rvflash/goup@v0.4.1
|
||||
|
||||
#goup -v ./...
|
||||
#go get github.com/psampaz/go-mod-outdated@v0.6.0
|
||||
go list -u -m -mod=mod -json all | go-mod-outdated -update -direct -ci || true
|
||||
|
||||
#go list -u -m -json all | go-mod-outdated -update
|
9
.github/workflows/build.yml
vendored
9
.github/workflows/build.yml
vendored
@@ -3,15 +3,16 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
- v3
|
||||
jobs:
|
||||
test:
|
||||
name: test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: setup
|
||||
uses: actions/setup-go@v1
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.15
|
||||
go-version: 1.16
|
||||
- name: cache
|
||||
uses: actions/cache@v2
|
||||
with:
|
||||
@@ -49,11 +50,11 @@ jobs:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v2
|
||||
- name: lint
|
||||
uses: golangci/golangci-lint-action@v1
|
||||
uses: golangci/golangci-lint-action@v2
|
||||
continue-on-error: true
|
||||
with:
|
||||
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
|
||||
version: v1.30
|
||||
version: v1.39
|
||||
# Optional: working directory, useful for monorepos
|
||||
# working-directory: somedir
|
||||
# Optional: golangci-lint command line arguments.
|
||||
|
78
.github/workflows/codeql-analysis.yml
vendored
Normal file
78
.github/workflows/codeql-analysis.yml
vendored
Normal file
@@ -0,0 +1,78 @@
|
||||
# For most projects, this workflow file will not need changing; you simply need
|
||||
# to commit it to your repository.
|
||||
#
|
||||
# You may wish to alter this file to override the set of languages analyzed,
|
||||
# or to provide custom queries or build logic.
|
||||
#
|
||||
# ******** NOTE ********
|
||||
# We have attempted to detect the languages in your repository. Please check
|
||||
# the `language` matrix defined below to confirm you have the correct set of
|
||||
# supported CodeQL languages.
|
||||
#
|
||||
name: "codeql"
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: ["prbuild"]
|
||||
types:
|
||||
- completed
|
||||
push:
|
||||
branches: [ master, v3 ]
|
||||
pull_request:
|
||||
# The branches below must be a subset of the branches above
|
||||
branches: [ master, v3 ]
|
||||
schedule:
|
||||
- cron: '34 1 * * 0'
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: analyze
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
security-events: write
|
||||
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
language: [ 'go' ]
|
||||
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ]
|
||||
# Learn more:
|
||||
# https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed
|
||||
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v2
|
||||
- name: setup
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.16
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: init
|
||||
uses: github/codeql-action/init@v1
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
# If you wish to specify custom queries, you can do so here or in a config file.
|
||||
# By default, queries listed here will override any specified in a config file.
|
||||
# Prefix the list here with "+" to use these queries and those in the config file.
|
||||
# queries: ./path/to/local/query, your-org/your-repo/queries@main
|
||||
|
||||
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
||||
# If this step fails, then you should remove it and run the build manually (see below)
|
||||
- name: autobuild
|
||||
uses: github/codeql-action/autobuild@v1
|
||||
|
||||
# ℹ️ Command-line programs to run using the OS shell.
|
||||
# 📚 https://git.io/JvXDl
|
||||
|
||||
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
|
||||
# and modify them (or add more) to build your code if your project
|
||||
# uses a compiled language
|
||||
|
||||
#- run: |
|
||||
# make bootstrap
|
||||
# make release
|
||||
|
||||
- name: analyze
|
||||
uses: github/codeql-action/analyze@v1
|
31
.github/workflows/dependabot-automerge.yml
vendored
Normal file
31
.github/workflows/dependabot-automerge.yml
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
name: "prautomerge"
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [assigned, opened, synchronize, reopened]
|
||||
|
||||
permissions:
|
||||
pull-requests: write
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
dependabot:
|
||||
runs-on: ubuntu-latest
|
||||
if: ${{ github.actor == 'dependabot[bot]' }}
|
||||
steps:
|
||||
- name: metadata
|
||||
id: metadata
|
||||
uses: dependabot/fetch-metadata@v1.1.1
|
||||
with:
|
||||
github-token: "${{ secrets.TOKEN }}"
|
||||
- name: approve
|
||||
run: gh pr review --approve "$PR_URL"
|
||||
env:
|
||||
PR_URL: ${{github.event.pull_request.html_url}}
|
||||
GITHUB_TOKEN: ${{secrets.TOKEN}}
|
||||
- name: merge
|
||||
if: ${{contains(steps.metadata.outputs.dependency-names, 'go.unistack.org')}}
|
||||
run: gh pr merge --auto --merge "$PR_URL"
|
||||
env:
|
||||
PR_URL: ${{github.event.pull_request.html_url}}
|
||||
GITHUB_TOKEN: ${{secrets.TOKEN}}
|
11
.github/workflows/pr.yml
vendored
11
.github/workflows/pr.yml
vendored
@@ -3,19 +3,20 @@ on:
|
||||
pull_request:
|
||||
branches:
|
||||
- master
|
||||
- v3
|
||||
jobs:
|
||||
test:
|
||||
name: test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: setup
|
||||
uses: actions/setup-go@v1
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.15
|
||||
go-version: 1.16
|
||||
- name: cache
|
||||
uses: actions/cache@v2
|
||||
with:
|
||||
path: ~/go/pkg/mod
|
||||
path: ~/go/pkg
|
||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||
restore-keys: ${{ runner.os }}-go-
|
||||
- name: sdk checkout
|
||||
@@ -49,11 +50,11 @@ jobs:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v2
|
||||
- name: lint
|
||||
uses: golangci/golangci-lint-action@v1
|
||||
uses: golangci/golangci-lint-action@v2
|
||||
continue-on-error: true
|
||||
with:
|
||||
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
|
||||
version: v1.30
|
||||
version: v1.39
|
||||
# Optional: working directory, useful for monorepos
|
||||
# working-directory: somedir
|
||||
# Optional: golangci-lint command line arguments.
|
||||
|
@@ -1,40 +1,44 @@
|
||||
run:
|
||||
concurrency: 4
|
||||
deadline: 5m
|
||||
modules-download-mode: readonly
|
||||
skip-dirs:
|
||||
- util/mdns.new
|
||||
skip-files:
|
||||
- ".*\\.pb\\.go$"
|
||||
- ".*\\.pb\\.micro\\.go$"
|
||||
issues-exit-code: 1
|
||||
tests: true
|
||||
|
||||
linters-settings:
|
||||
govet:
|
||||
check-shadowing: true
|
||||
enable:
|
||||
- fieldalignment
|
||||
|
||||
linters:
|
||||
disable-all: false
|
||||
enable-all: false
|
||||
enable:
|
||||
- megacheck
|
||||
- staticcheck
|
||||
- deadcode
|
||||
- varcheck
|
||||
- gosimple
|
||||
- unused
|
||||
- prealloc
|
||||
- scopelint
|
||||
- gocritic
|
||||
- goimports
|
||||
- unconvert
|
||||
- govet
|
||||
- nakedret
|
||||
- deadcode
|
||||
- errcheck
|
||||
- govet
|
||||
- ineffassign
|
||||
- staticcheck
|
||||
- structcheck
|
||||
- gosec
|
||||
disable:
|
||||
- maligned
|
||||
- interfacer
|
||||
- typecheck
|
||||
- dupl
|
||||
output:
|
||||
format: colored-line-number
|
||||
# print lines of code with issue, default is true
|
||||
print-issued-lines: true
|
||||
# print linter name in the end of issue text, default is true
|
||||
print-linter-name: true
|
||||
# make issues output unique by line, default is true
|
||||
uniq-by-line: true
|
||||
- unused
|
||||
- varcheck
|
||||
- bodyclose
|
||||
- gci
|
||||
- goconst
|
||||
- gocritic
|
||||
- gosimple
|
||||
- gofmt
|
||||
- gofumpt
|
||||
- goimports
|
||||
- revive
|
||||
- gosec
|
||||
- makezero
|
||||
- misspell
|
||||
- nakedret
|
||||
- nestif
|
||||
- nilerr
|
||||
- noctx
|
||||
- prealloc
|
||||
- unconvert
|
||||
- unparam
|
||||
disable-all: false
|
||||
|
@@ -1,4 +1,4 @@
|
||||
# Micro [](https://opensource.org/licenses/Apache-2.0) [](https://pkg.go.dev/github.com/unistack-org/micro/v3?tab=overview) [](https://github.com/unistack-org/micro/actions?query=workflow%3Abuild+branch%3Amaster+event%3Apush) [](https://goreportcard.com/report/github.com/unistack-org/micro) [](https://unistack-org.slack.com/messages/default)
|
||||
# Micro [](https://opensource.org/licenses/Apache-2.0) [](https://pkg.go.dev/github.com/unistack-org/micro/v3?tab=overview) [](https://github.com/unistack-org/micro/actions?query=workflow%3Abuild+branch%3Amaster+event%3Apush) [](https://goreportcard.com/report/go.unistack.org/micro/v3) [](https://unistack-org.slack.com/messages/default)
|
||||
|
||||
Micro is a standard library for microservices.
|
||||
|
||||
|
15
SECURITY.md
Normal file
15
SECURITY.md
Normal file
@@ -0,0 +1,15 @@
|
||||
# Security Policy
|
||||
|
||||
## Supported Versions
|
||||
|
||||
Use this section to tell people about which versions of your project are
|
||||
currently being supported with security updates.
|
||||
|
||||
| Version | Supported |
|
||||
| ------- | ------------------ |
|
||||
| 3.7.x | :white_check_mark: |
|
||||
| < 3.7.0 | :x: |
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
If you find any issue, please create github issue in this repo
|
62
api/api.go
62
api/api.go
@@ -1,15 +1,17 @@
|
||||
package api
|
||||
package api // import "go.unistack.org/micro/v3/api"
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/unistack-org/micro/v3/metadata"
|
||||
"github.com/unistack-org/micro/v3/register"
|
||||
"github.com/unistack-org/micro/v3/server"
|
||||
"go.unistack.org/micro/v3/metadata"
|
||||
"go.unistack.org/micro/v3/register"
|
||||
"go.unistack.org/micro/v3/server"
|
||||
)
|
||||
|
||||
// nolint: revive
|
||||
// Api interface
|
||||
type Api interface {
|
||||
// Initialise options
|
||||
Init(...Option) error
|
||||
@@ -23,28 +25,30 @@ type Api interface {
|
||||
String() string
|
||||
}
|
||||
|
||||
// Options holds the options
|
||||
type Options struct{}
|
||||
|
||||
// Option func signature
|
||||
type Option func(*Options) error
|
||||
|
||||
// Endpoint is a mapping between an RPC method and HTTP endpoint
|
||||
type Endpoint struct {
|
||||
// RPC Method e.g. Greeter.Hello
|
||||
// Name Greeter.Hello
|
||||
Name string
|
||||
// Description e.g what's this endpoint for
|
||||
// Desciption for endpoint
|
||||
Description string
|
||||
// API Handler e.g rpc, proxy
|
||||
// Handler e.g rpc, proxy
|
||||
Handler string
|
||||
// HTTP Host e.g example.com
|
||||
Host []string
|
||||
// HTTP Methods e.g GET, POST
|
||||
Method []string
|
||||
// HTTP Path e.g /greeter. Expect POSIX regex
|
||||
Path []string
|
||||
// Body destination
|
||||
// "*" or "" - top level message value
|
||||
// "string" - inner message value
|
||||
Body string
|
||||
// Host e.g example.com
|
||||
Host []string
|
||||
// Method e.g GET, POST
|
||||
Method []string
|
||||
// Path e.g /greeter. Expect POSIX regex
|
||||
Path []string
|
||||
// Stream flag
|
||||
Stream bool
|
||||
}
|
||||
@@ -53,28 +57,12 @@ type Endpoint struct {
|
||||
type Service struct {
|
||||
// Name of service
|
||||
Name string
|
||||
// The endpoint for this service
|
||||
// Endpoint for this service
|
||||
Endpoint *Endpoint
|
||||
// Versions of this service
|
||||
// Services that provides service
|
||||
Services []*register.Service
|
||||
}
|
||||
|
||||
func strip(s string) string {
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
|
||||
func slice(s string) []string {
|
||||
var sl []string
|
||||
|
||||
for _, p := range strings.Split(s, ",") {
|
||||
if str := strip(p); len(str) > 0 {
|
||||
sl = append(sl, strip(p))
|
||||
}
|
||||
}
|
||||
|
||||
return sl
|
||||
}
|
||||
|
||||
// Encode encodes an endpoint to endpoint metadata
|
||||
func Encode(e *Endpoint) map[string]string {
|
||||
if e == nil {
|
||||
@@ -98,6 +86,7 @@ func Encode(e *Endpoint) map[string]string {
|
||||
set("method", strings.Join(e.Method, ","))
|
||||
set("path", strings.Join(e.Path, ","))
|
||||
set("host", strings.Join(e.Host, ","))
|
||||
set("body", e.Body)
|
||||
|
||||
return ep
|
||||
}
|
||||
@@ -118,6 +107,7 @@ func Decode(e metadata.Metadata) *Endpoint {
|
||||
ephost, _ := e.Get("host")
|
||||
ep.Host = []string{ephost}
|
||||
ep.Handler, _ = e.Get("handler")
|
||||
ep.Body, _ = e.Get("body")
|
||||
|
||||
return ep
|
||||
}
|
||||
@@ -136,14 +126,14 @@ func Validate(e *Endpoint) error {
|
||||
ps := p[0]
|
||||
pe := p[len(p)-1]
|
||||
|
||||
if ps == '^' && pe == '$' {
|
||||
_, err := regexp.CompilePOSIX(p)
|
||||
if err != nil {
|
||||
switch {
|
||||
case ps == '^' && pe == '$':
|
||||
if _, err := regexp.CompilePOSIX(p); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if ps == '^' && pe != '$' {
|
||||
case ps == '^' && pe != '$':
|
||||
return errors.New("invalid path")
|
||||
} else if ps != '^' && pe == '$' {
|
||||
case ps != '^' && pe == '$':
|
||||
return errors.New("invalid path")
|
||||
}
|
||||
}
|
||||
|
@@ -5,6 +5,7 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
//nolint:gocyclo
|
||||
func TestEncoding(t *testing.T) {
|
||||
testData := []*Endpoint{
|
||||
nil,
|
||||
@@ -148,5 +149,4 @@ func TestValidate(t *testing.T) {
|
||||
if err := Validate(epPcreInvalid); err == nil {
|
||||
t.Fatalf("invalid pcre %v", epPcreInvalid.Path[0])
|
||||
}
|
||||
|
||||
}
|
||||
|
@@ -1,121 +0,0 @@
|
||||
// Package api provides an http-rpc handler which provides the entire http request over rpc
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
goapi "github.com/unistack-org/micro/v3/api"
|
||||
"github.com/unistack-org/micro/v3/api/handler"
|
||||
api "github.com/unistack-org/micro/v3/api/proto"
|
||||
"github.com/unistack-org/micro/v3/client"
|
||||
"github.com/unistack-org/micro/v3/errors"
|
||||
"github.com/unistack-org/micro/v3/util/ctx"
|
||||
"github.com/unistack-org/micro/v3/util/router"
|
||||
)
|
||||
|
||||
type apiHandler struct {
|
||||
opts handler.Options
|
||||
s *goapi.Service
|
||||
}
|
||||
|
||||
const (
|
||||
Handler = "api"
|
||||
)
|
||||
|
||||
// API handler is the default handler which takes api.Request and returns api.Response
|
||||
func (a *apiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
bsize := handler.DefaultMaxRecvSize
|
||||
if a.opts.MaxRecvSize > 0 {
|
||||
bsize = a.opts.MaxRecvSize
|
||||
}
|
||||
|
||||
r.Body = http.MaxBytesReader(w, r.Body, bsize)
|
||||
request, err := requestToProto(r)
|
||||
if err != nil {
|
||||
er := errors.InternalServerError("go.micro.api", err.Error())
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(500)
|
||||
w.Write([]byte(er.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
var service *goapi.Service
|
||||
|
||||
if a.s != nil {
|
||||
// we were given the service
|
||||
service = a.s
|
||||
} else if a.opts.Router != nil {
|
||||
// try get service from router
|
||||
s, err := a.opts.Router.Route(r)
|
||||
if err != nil {
|
||||
er := errors.InternalServerError("go.micro.api", err.Error())
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(500)
|
||||
w.Write([]byte(er.Error()))
|
||||
return
|
||||
}
|
||||
service = s
|
||||
} else {
|
||||
// we have no way of routing the request
|
||||
er := errors.InternalServerError("go.micro.api", "no route found")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(500)
|
||||
w.Write([]byte(er.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// create request and response
|
||||
c := a.opts.Client
|
||||
req := c.NewRequest(service.Name, service.Endpoint.Name, request)
|
||||
rsp := &api.Response{}
|
||||
|
||||
// create the context from headers
|
||||
cx := ctx.FromRequest(r)
|
||||
|
||||
if err := c.Call(cx, req, rsp, client.WithRouter(router.New(service.Services))); err != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
ce := errors.Parse(err.Error())
|
||||
switch ce.Code {
|
||||
case 0:
|
||||
w.WriteHeader(500)
|
||||
default:
|
||||
w.WriteHeader(int(ce.Code))
|
||||
}
|
||||
w.Write([]byte(ce.Error()))
|
||||
return
|
||||
} else if rsp.StatusCode == 0 {
|
||||
rsp.StatusCode = http.StatusOK
|
||||
}
|
||||
|
||||
for _, header := range rsp.GetHeader() {
|
||||
for _, val := range header.Values {
|
||||
w.Header().Add(header.Key, val)
|
||||
}
|
||||
}
|
||||
|
||||
if len(w.Header().Get("Content-Type")) == 0 {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
}
|
||||
|
||||
w.WriteHeader(int(rsp.StatusCode))
|
||||
w.Write([]byte(rsp.Body))
|
||||
}
|
||||
|
||||
func (a *apiHandler) String() string {
|
||||
return "api"
|
||||
}
|
||||
|
||||
func NewHandler(opts ...handler.Option) handler.Handler {
|
||||
options := handler.NewOptions(opts...)
|
||||
return &apiHandler{
|
||||
opts: options,
|
||||
}
|
||||
}
|
||||
|
||||
func WithService(s *goapi.Service, opts ...handler.Option) handler.Handler {
|
||||
options := handler.NewOptions(opts...)
|
||||
return &apiHandler{
|
||||
opts: options,
|
||||
s: s,
|
||||
}
|
||||
}
|
@@ -1,109 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"mime"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/oxtoacart/bpool"
|
||||
api "github.com/unistack-org/micro/v3/api/proto"
|
||||
)
|
||||
|
||||
var (
|
||||
// need to calculate later to specify useful defaults
|
||||
bufferPool = bpool.NewSizedBufferPool(1024, 8)
|
||||
)
|
||||
|
||||
func requestToProto(r *http.Request) (*api.Request, error) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
return nil, fmt.Errorf("Error parsing form: %v", err)
|
||||
}
|
||||
|
||||
req := &api.Request{
|
||||
Path: r.URL.Path,
|
||||
Method: r.Method,
|
||||
Header: make(map[string]*api.Pair),
|
||||
Get: make(map[string]*api.Pair),
|
||||
Post: make(map[string]*api.Pair),
|
||||
Url: r.URL.String(),
|
||||
}
|
||||
|
||||
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
ct = "text/plain; charset=UTF-8" //default CT is text/plain
|
||||
r.Header.Set("Content-Type", ct)
|
||||
}
|
||||
|
||||
//set the body:
|
||||
if r.Body != nil {
|
||||
switch ct {
|
||||
case "application/x-www-form-urlencoded":
|
||||
// expect form vals in Post data
|
||||
default:
|
||||
buf := bufferPool.Get()
|
||||
defer bufferPool.Put(buf)
|
||||
if _, err = buf.ReadFrom(r.Body); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Body = buf.String()
|
||||
}
|
||||
}
|
||||
|
||||
// Set X-Forwarded-For if it does not exist
|
||||
if ip, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
|
||||
if prior, ok := r.Header["X-Forwarded-For"]; ok {
|
||||
ip = strings.Join(prior, ", ") + ", " + ip
|
||||
}
|
||||
|
||||
// Set the header
|
||||
req.Header["X-Forwarded-For"] = &api.Pair{
|
||||
Key: "X-Forwarded-For",
|
||||
Values: []string{ip},
|
||||
}
|
||||
}
|
||||
|
||||
// Host is stripped from net/http Headers so let's add it
|
||||
req.Header["Host"] = &api.Pair{
|
||||
Key: "Host",
|
||||
Values: []string{r.Host},
|
||||
}
|
||||
|
||||
// Get data
|
||||
for key, vals := range r.URL.Query() {
|
||||
header, ok := req.Get[key]
|
||||
if !ok {
|
||||
header = &api.Pair{
|
||||
Key: key,
|
||||
}
|
||||
req.Get[key] = header
|
||||
}
|
||||
header.Values = vals
|
||||
}
|
||||
|
||||
// Post data
|
||||
for key, vals := range r.PostForm {
|
||||
header, ok := req.Post[key]
|
||||
if !ok {
|
||||
header = &api.Pair{
|
||||
Key: key,
|
||||
}
|
||||
req.Post[key] = header
|
||||
}
|
||||
header.Values = vals
|
||||
}
|
||||
|
||||
for key, vals := range r.Header {
|
||||
header, ok := req.Header[key]
|
||||
if !ok {
|
||||
header = &api.Pair{
|
||||
Key: key,
|
||||
}
|
||||
req.Header[key] = header
|
||||
}
|
||||
header.Values = vals
|
||||
}
|
||||
|
||||
return req, nil
|
||||
}
|
@@ -1,46 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRequestToProto(t *testing.T) {
|
||||
testData := []*http.Request{
|
||||
{
|
||||
Method: "GET",
|
||||
Header: http.Header{
|
||||
"Header": []string{"test"},
|
||||
},
|
||||
URL: &url.URL{
|
||||
Scheme: "http",
|
||||
Host: "localhost",
|
||||
Path: "/foo/bar",
|
||||
RawQuery: "param1=value1",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, d := range testData {
|
||||
p, err := requestToProto(d)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p.Path != d.URL.Path {
|
||||
t.Fatalf("Expected path %s got %s", d.URL.Path, p.Path)
|
||||
}
|
||||
if p.Method != d.Method {
|
||||
t.Fatalf("Expected method %s got %s", d.Method, p.Method)
|
||||
}
|
||||
for k, v := range d.Header {
|
||||
if val, ok := p.Header[k]; !ok {
|
||||
t.Fatalf("Expected header %s", k)
|
||||
} else {
|
||||
if val.Values[0] != v[0] {
|
||||
t.Fatalf("Expected val %s, got %s", val.Values[0], v[0])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,141 +0,0 @@
|
||||
// Package event provides a handler which publishes an event
|
||||
package event
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/oxtoacart/bpool"
|
||||
"github.com/unistack-org/micro/v3/api/handler"
|
||||
proto "github.com/unistack-org/micro/v3/api/proto"
|
||||
"github.com/unistack-org/micro/v3/util/ctx"
|
||||
)
|
||||
|
||||
var (
|
||||
bufferPool = bpool.NewSizedBufferPool(1024, 8)
|
||||
)
|
||||
|
||||
type event struct {
|
||||
opts handler.Options
|
||||
}
|
||||
|
||||
var (
|
||||
Handler = "event"
|
||||
versionRe = regexp.MustCompilePOSIX("^v[0-9]+$")
|
||||
)
|
||||
|
||||
func eventName(parts []string) string {
|
||||
return strings.Join(parts, ".")
|
||||
}
|
||||
|
||||
func evRoute(ns, p string) (string, string) {
|
||||
p = path.Clean(p)
|
||||
p = strings.TrimPrefix(p, "/")
|
||||
|
||||
if len(p) == 0 {
|
||||
return ns, "event"
|
||||
}
|
||||
|
||||
parts := strings.Split(p, "/")
|
||||
|
||||
// no path
|
||||
if len(parts) == 0 {
|
||||
// topic: namespace
|
||||
// action: event
|
||||
return strings.Trim(ns, "."), "event"
|
||||
}
|
||||
|
||||
// Treat /v[0-9]+ as versioning
|
||||
// /v1/foo/bar => topic: v1.foo action: bar
|
||||
if len(parts) >= 2 && versionRe.Match([]byte(parts[0])) {
|
||||
topic := ns + "." + strings.Join(parts[:2], ".")
|
||||
action := eventName(parts[1:])
|
||||
return topic, action
|
||||
}
|
||||
|
||||
// /foo => topic: ns.foo action: foo
|
||||
// /foo/bar => topic: ns.foo action: bar
|
||||
topic := ns + "." + strings.Join(parts[:1], ".")
|
||||
action := eventName(parts[1:])
|
||||
|
||||
return topic, action
|
||||
}
|
||||
|
||||
func (e *event) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
bsize := handler.DefaultMaxRecvSize
|
||||
if e.opts.MaxRecvSize > 0 {
|
||||
bsize = e.opts.MaxRecvSize
|
||||
}
|
||||
|
||||
r.Body = http.MaxBytesReader(w, r.Body, bsize)
|
||||
|
||||
// request to topic:event
|
||||
// create event
|
||||
// publish to topic
|
||||
|
||||
topic, action := evRoute(e.opts.Namespace, r.URL.Path)
|
||||
|
||||
// create event
|
||||
ev := &proto.Event{
|
||||
Name: action,
|
||||
// TODO: dedupe event
|
||||
Id: fmt.Sprintf("%s-%s-%s", topic, action, uuid.New().String()),
|
||||
Header: make(map[string]*proto.Pair),
|
||||
Timestamp: time.Now().Unix(),
|
||||
}
|
||||
|
||||
// set headers
|
||||
for key, vals := range r.Header {
|
||||
header, ok := ev.Header[key]
|
||||
if !ok {
|
||||
header = &proto.Pair{
|
||||
Key: key,
|
||||
}
|
||||
ev.Header[key] = header
|
||||
}
|
||||
header.Values = vals
|
||||
}
|
||||
|
||||
// set body
|
||||
if r.Method == "GET" {
|
||||
bytes, _ := json.Marshal(r.URL.Query())
|
||||
ev.Data = string(bytes)
|
||||
} else {
|
||||
// Read body
|
||||
buf := bufferPool.Get()
|
||||
defer bufferPool.Put(buf)
|
||||
if _, err := buf.ReadFrom(r.Body); err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
ev.Data = buf.String()
|
||||
}
|
||||
|
||||
// get client
|
||||
c := e.opts.Client
|
||||
|
||||
// create publication
|
||||
p := c.NewMessage(topic, ev)
|
||||
|
||||
// publish event
|
||||
if err := c.Publish(ctx.FromRequest(r), p); err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (e *event) String() string {
|
||||
return "event"
|
||||
}
|
||||
|
||||
func NewHandler(opts ...handler.Option) handler.Handler {
|
||||
return &event{
|
||||
opts: handler.NewOptions(opts...),
|
||||
}
|
||||
}
|
@@ -1,5 +1,5 @@
|
||||
// Package handler provides http handlers
|
||||
package handler
|
||||
package handler // import "go.unistack.org/micro/v3/api/handler"
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
@@ -1,105 +0,0 @@
|
||||
// Package http is a http reverse proxy handler
|
||||
package http
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
|
||||
"github.com/unistack-org/micro/v3/api"
|
||||
"github.com/unistack-org/micro/v3/api/handler"
|
||||
"github.com/unistack-org/micro/v3/register"
|
||||
)
|
||||
|
||||
const (
|
||||
Handler = "http"
|
||||
)
|
||||
|
||||
type httpHandler struct {
|
||||
options handler.Options
|
||||
|
||||
// set with different initializer
|
||||
s *api.Service
|
||||
}
|
||||
|
||||
func (h *httpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
service, err := h.getService(r)
|
||||
if err != nil {
|
||||
w.WriteHeader(500)
|
||||
return
|
||||
}
|
||||
|
||||
if len(service) == 0 {
|
||||
w.WriteHeader(404)
|
||||
return
|
||||
}
|
||||
|
||||
rp, err := url.Parse(service)
|
||||
if err != nil {
|
||||
w.WriteHeader(500)
|
||||
return
|
||||
}
|
||||
|
||||
httputil.NewSingleHostReverseProxy(rp).ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// getService returns the service for this request from the selector
|
||||
func (h *httpHandler) getService(r *http.Request) (string, error) {
|
||||
var service *api.Service
|
||||
|
||||
if h.s != nil {
|
||||
// we were given the service
|
||||
service = h.s
|
||||
} else if h.options.Router != nil {
|
||||
// try get service from router
|
||||
s, err := h.options.Router.Route(r)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
service = s
|
||||
} else {
|
||||
// we have no way of routing the request
|
||||
return "", errors.New("no route found")
|
||||
}
|
||||
|
||||
if len(service.Services) == 0 {
|
||||
return "", errors.New("no route found")
|
||||
}
|
||||
|
||||
// get the nodes for this service
|
||||
nodes := make([]*register.Node, 0, len(service.Services))
|
||||
for _, srv := range service.Services {
|
||||
nodes = append(nodes, srv.Nodes...)
|
||||
}
|
||||
|
||||
// select a random node
|
||||
node := nodes[rand.Int()%len(nodes)]
|
||||
|
||||
return fmt.Sprintf("http://%s", node.Address), nil
|
||||
}
|
||||
|
||||
func (h *httpHandler) String() string {
|
||||
return "http"
|
||||
}
|
||||
|
||||
// NewHandler returns a http proxy handler
|
||||
func NewHandler(opts ...handler.Option) handler.Handler {
|
||||
options := handler.NewOptions(opts...)
|
||||
|
||||
return &httpHandler{
|
||||
options: options,
|
||||
}
|
||||
}
|
||||
|
||||
// WithService creates a handler with a service
|
||||
func WithService(s *api.Service, opts ...handler.Option) handler.Handler {
|
||||
options := handler.NewOptions(opts...)
|
||||
|
||||
return &httpHandler{
|
||||
options: options,
|
||||
s: s,
|
||||
}
|
||||
}
|
@@ -1,129 +0,0 @@
|
||||
// +build ignore
|
||||
|
||||
package http
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/unistack-org/micro/v3/api/handler"
|
||||
"github.com/unistack-org/micro/v3/api/resolver"
|
||||
"github.com/unistack-org/micro/v3/api/resolver/vpath"
|
||||
"github.com/unistack-org/micro/v3/api/router"
|
||||
regRouter "github.com/unistack-org/micro/v3/api/router/register"
|
||||
"github.com/unistack-org/micro/v3/register"
|
||||
"github.com/unistack-org/micro/v3/register/memory"
|
||||
)
|
||||
|
||||
func testHttp(t *testing.T, path, service, ns string) {
|
||||
r := memory.NewRegister()
|
||||
|
||||
l, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer l.Close()
|
||||
|
||||
s := ®ister.Service{
|
||||
Name: service,
|
||||
Nodes: []*register.Node{
|
||||
{
|
||||
Id: service + "-1",
|
||||
Address: l.Addr().String(),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
r.Register(s)
|
||||
defer r.Deregister(s)
|
||||
|
||||
// setup the test handler
|
||||
m := http.NewServeMux()
|
||||
m.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte(`you got served`))
|
||||
})
|
||||
|
||||
// start http test serve
|
||||
go http.Serve(l, m)
|
||||
|
||||
// create new request and writer
|
||||
w := httptest.NewRecorder()
|
||||
req, err := http.NewRequest("POST", path, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// initialise the handler
|
||||
rt := regRouter.NewRouter(
|
||||
router.WithHandler("http"),
|
||||
router.WithRegister(r),
|
||||
router.WithResolver(vpath.NewResolver(
|
||||
resolver.WithServicePrefix(ns),
|
||||
)),
|
||||
)
|
||||
|
||||
p := NewHandler(handler.WithRouter(rt))
|
||||
|
||||
// execute the handler
|
||||
p.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("Expected 200 response got %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
if w.Body.String() != "you got served" {
|
||||
t.Fatalf("Expected body: you got served. Got: %s", w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHttpHandler(t *testing.T) {
|
||||
testData := []struct {
|
||||
path string
|
||||
service string
|
||||
namespace string
|
||||
}{
|
||||
{
|
||||
"/test/foo",
|
||||
"go.micro.api.test",
|
||||
"go.micro.api",
|
||||
},
|
||||
{
|
||||
"/test/foo/baz",
|
||||
"go.micro.api.test",
|
||||
"go.micro.api",
|
||||
},
|
||||
{
|
||||
"/v1/foo",
|
||||
"go.micro.api.v1.foo",
|
||||
"go.micro.api",
|
||||
},
|
||||
{
|
||||
"/v1/foo/bar",
|
||||
"go.micro.api.v1.foo",
|
||||
"go.micro.api",
|
||||
},
|
||||
{
|
||||
"/v2/baz",
|
||||
"go.micro.api.v2.baz",
|
||||
"go.micro.api",
|
||||
},
|
||||
{
|
||||
"/v2/baz/bar",
|
||||
"go.micro.api.v2.baz",
|
||||
"go.micro.api",
|
||||
},
|
||||
{
|
||||
"/v2/baz/bar",
|
||||
"v2.baz",
|
||||
"",
|
||||
},
|
||||
}
|
||||
|
||||
for _, d := range testData {
|
||||
t.Run(d.service, func(t *testing.T) {
|
||||
testHttp(t, d.path, d.service, d.namespace)
|
||||
})
|
||||
}
|
||||
}
|
@@ -1,26 +1,34 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"github.com/unistack-org/micro/v3/api/router"
|
||||
"github.com/unistack-org/micro/v3/client"
|
||||
"go.unistack.org/micro/v3/api/router"
|
||||
"go.unistack.org/micro/v3/client"
|
||||
"go.unistack.org/micro/v3/logger"
|
||||
)
|
||||
|
||||
var (
|
||||
DefaultMaxRecvSize int64 = 1024 * 1024 * 100 // 10Mb
|
||||
)
|
||||
// DefaultMaxRecvSize specifies max recv size for handler
|
||||
var DefaultMaxRecvSize int64 = 1024 * 1024 * 100 // 10Mb
|
||||
|
||||
// Options struct holds handler options
|
||||
type Options struct {
|
||||
MaxRecvSize int64
|
||||
Namespace string
|
||||
Router router.Router
|
||||
Client client.Client
|
||||
Logger logger.Logger
|
||||
Namespace string
|
||||
MaxRecvSize int64
|
||||
}
|
||||
|
||||
// Option func signature
|
||||
type Option func(o *Options)
|
||||
|
||||
// NewOptions fills in the blanks
|
||||
// NewOptions creates new options struct and fills it
|
||||
func NewOptions(opts ...Option) Options {
|
||||
var options Options
|
||||
options := Options{
|
||||
Client: client.DefaultClient,
|
||||
Router: router.DefaultRouter,
|
||||
Logger: logger.DefaultLogger,
|
||||
MaxRecvSize: DefaultMaxRecvSize,
|
||||
}
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
@@ -30,10 +38,6 @@ func NewOptions(opts ...Option) Options {
|
||||
WithNamespace("go.micro.api")(&options)
|
||||
}
|
||||
|
||||
if options.MaxRecvSize == 0 {
|
||||
options.MaxRecvSize = DefaultMaxRecvSize
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
@@ -51,6 +55,7 @@ func WithRouter(r router.Router) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// WithClient specifies client to be used by the handler
|
||||
func WithClient(c client.Client) Option {
|
||||
return func(o *Options) {
|
||||
o.Client = c
|
||||
|
@@ -1,182 +0,0 @@
|
||||
// Package web contains the web handler including websocket support
|
||||
package web
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/unistack-org/micro/v3/api"
|
||||
"github.com/unistack-org/micro/v3/api/handler"
|
||||
"github.com/unistack-org/micro/v3/register"
|
||||
)
|
||||
|
||||
const (
|
||||
Handler = "web"
|
||||
)
|
||||
|
||||
type webHandler struct {
|
||||
opts handler.Options
|
||||
s *api.Service
|
||||
}
|
||||
|
||||
func (wh *webHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
service, err := wh.getService(r)
|
||||
if err != nil {
|
||||
w.WriteHeader(500)
|
||||
return
|
||||
}
|
||||
|
||||
if len(service) == 0 {
|
||||
w.WriteHeader(404)
|
||||
return
|
||||
}
|
||||
|
||||
rp, err := url.Parse(service)
|
||||
if err != nil {
|
||||
w.WriteHeader(500)
|
||||
return
|
||||
}
|
||||
|
||||
if isWebSocket(r) {
|
||||
wh.serveWebSocket(rp.Host, w, r)
|
||||
return
|
||||
}
|
||||
|
||||
httputil.NewSingleHostReverseProxy(rp).ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// getService returns the service for this request from the selector
|
||||
func (wh *webHandler) getService(r *http.Request) (string, error) {
|
||||
var service *api.Service
|
||||
|
||||
if wh.s != nil {
|
||||
// we were given the service
|
||||
service = wh.s
|
||||
} else if wh.opts.Router != nil {
|
||||
// try get service from router
|
||||
s, err := wh.opts.Router.Route(r)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
service = s
|
||||
} else {
|
||||
// we have no way of routing the request
|
||||
return "", errors.New("no route found")
|
||||
}
|
||||
|
||||
// get the nodes
|
||||
nodes := make([]*register.Node, 0, len(service.Services))
|
||||
for _, srv := range service.Services {
|
||||
nodes = append(nodes, srv.Nodes...)
|
||||
}
|
||||
|
||||
if len(nodes) == 0 {
|
||||
return "", errors.New("no route found")
|
||||
}
|
||||
|
||||
// select a random node
|
||||
node := nodes[rand.Int()%len(nodes)]
|
||||
|
||||
return fmt.Sprintf("http://%s", node.Address), nil
|
||||
}
|
||||
|
||||
// serveWebSocket used to serve a web socket proxied connection
|
||||
func (wh *webHandler) serveWebSocket(host string, w http.ResponseWriter, r *http.Request) {
|
||||
req := new(http.Request)
|
||||
*req = *r
|
||||
|
||||
if len(host) == 0 {
|
||||
http.Error(w, "invalid host", 500)
|
||||
return
|
||||
}
|
||||
|
||||
// set x-forward-for
|
||||
if clientIP, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
|
||||
if ips, ok := req.Header["X-Forwarded-For"]; ok {
|
||||
clientIP = strings.Join(ips, ", ") + ", " + clientIP
|
||||
}
|
||||
req.Header.Set("X-Forwarded-For", clientIP)
|
||||
}
|
||||
|
||||
// connect to the backend host
|
||||
conn, err := net.Dial("tcp", host)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
|
||||
// hijack the connection
|
||||
hj, ok := w.(http.Hijacker)
|
||||
if !ok {
|
||||
http.Error(w, "failed to connect", 500)
|
||||
return
|
||||
}
|
||||
|
||||
nc, _, err := hj.Hijack()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
defer nc.Close()
|
||||
defer conn.Close()
|
||||
|
||||
if err = req.Write(conn); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
errCh := make(chan error, 2)
|
||||
|
||||
cp := func(dst io.Writer, src io.Reader) {
|
||||
_, err := io.Copy(dst, src)
|
||||
errCh <- err
|
||||
}
|
||||
|
||||
go cp(conn, nc)
|
||||
go cp(nc, conn)
|
||||
|
||||
<-errCh
|
||||
}
|
||||
|
||||
func isWebSocket(r *http.Request) bool {
|
||||
contains := func(key, val string) bool {
|
||||
vv := strings.Split(r.Header.Get(key), ",")
|
||||
for _, v := range vv {
|
||||
if val == strings.ToLower(strings.TrimSpace(v)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
if contains("Connection", "upgrade") && contains("Upgrade", "websocket") {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (wh *webHandler) String() string {
|
||||
return "web"
|
||||
}
|
||||
|
||||
func NewHandler(opts ...handler.Option) handler.Handler {
|
||||
return &webHandler{
|
||||
opts: handler.NewOptions(opts...),
|
||||
}
|
||||
}
|
||||
|
||||
func WithService(s *api.Service, opts ...handler.Option) handler.Handler {
|
||||
options := handler.NewOptions(opts...)
|
||||
|
||||
return &webHandler{
|
||||
opts: options,
|
||||
s: s,
|
||||
}
|
||||
}
|
@@ -1,28 +0,0 @@
|
||||
package proto
|
||||
|
||||
type Message struct {
|
||||
data []byte
|
||||
}
|
||||
|
||||
func (m *Message) ProtoMessage() {}
|
||||
|
||||
func (m *Message) Reset() {
|
||||
*m = Message{}
|
||||
}
|
||||
|
||||
func (m *Message) String() string {
|
||||
return string(m.data)
|
||||
}
|
||||
|
||||
func (m *Message) Marshal() ([]byte, error) {
|
||||
return m.data, nil
|
||||
}
|
||||
|
||||
func (m *Message) Unmarshal(data []byte) error {
|
||||
m.data = data
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewMessage(data []byte) *Message {
|
||||
return &Message{data}
|
||||
}
|
@@ -1,511 +0,0 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.25.0
|
||||
// protoc v3.6.1
|
||||
// source: api/proto/api.proto
|
||||
|
||||
package go_api
|
||||
|
||||
import (
|
||||
proto "github.com/golang/protobuf/proto"
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
// This is a compile-time assertion that a sufficiently up-to-date version
|
||||
// of the legacy proto package is being used.
|
||||
const _ = proto.ProtoPackageIsVersion4
|
||||
|
||||
type Pair struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"`
|
||||
Values []string `protobuf:"bytes,2,rep,name=values,proto3" json:"values,omitempty"`
|
||||
}
|
||||
|
||||
func (x *Pair) Reset() {
|
||||
*x = Pair{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_api_proto_api_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *Pair) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Pair) ProtoMessage() {}
|
||||
|
||||
func (x *Pair) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_api_proto_api_proto_msgTypes[0]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Pair.ProtoReflect.Descriptor instead.
|
||||
func (*Pair) Descriptor() ([]byte, []int) {
|
||||
return file_api_proto_api_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *Pair) GetKey() string {
|
||||
if x != nil {
|
||||
return x.Key
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Pair) GetValues() []string {
|
||||
if x != nil {
|
||||
return x.Values
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// A HTTP request as RPC
|
||||
// Forward by the api handler
|
||||
type Request struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
Method string `protobuf:"bytes,1,opt,name=method,proto3" json:"method,omitempty"`
|
||||
Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"`
|
||||
Header map[string]*Pair `protobuf:"bytes,3,rep,name=header,proto3" json:"header,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
||||
Get map[string]*Pair `protobuf:"bytes,4,rep,name=get,proto3" json:"get,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
||||
Post map[string]*Pair `protobuf:"bytes,5,rep,name=post,proto3" json:"post,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
||||
Body string `protobuf:"bytes,6,opt,name=body,proto3" json:"body,omitempty"` // raw request body; if not application/x-www-form-urlencoded
|
||||
Url string `protobuf:"bytes,7,opt,name=url,proto3" json:"url,omitempty"`
|
||||
}
|
||||
|
||||
func (x *Request) Reset() {
|
||||
*x = Request{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_api_proto_api_proto_msgTypes[1]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *Request) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Request) ProtoMessage() {}
|
||||
|
||||
func (x *Request) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_api_proto_api_proto_msgTypes[1]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Request.ProtoReflect.Descriptor instead.
|
||||
func (*Request) Descriptor() ([]byte, []int) {
|
||||
return file_api_proto_api_proto_rawDescGZIP(), []int{1}
|
||||
}
|
||||
|
||||
func (x *Request) GetMethod() string {
|
||||
if x != nil {
|
||||
return x.Method
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Request) GetPath() string {
|
||||
if x != nil {
|
||||
return x.Path
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Request) GetHeader() map[string]*Pair {
|
||||
if x != nil {
|
||||
return x.Header
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Request) GetGet() map[string]*Pair {
|
||||
if x != nil {
|
||||
return x.Get
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Request) GetPost() map[string]*Pair {
|
||||
if x != nil {
|
||||
return x.Post
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Request) GetBody() string {
|
||||
if x != nil {
|
||||
return x.Body
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Request) GetUrl() string {
|
||||
if x != nil {
|
||||
return x.Url
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// A HTTP response as RPC
|
||||
// Expected response for the api handler
|
||||
type Response struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
StatusCode int32 `protobuf:"varint,1,opt,name=statusCode,proto3" json:"statusCode,omitempty"`
|
||||
Header map[string]*Pair `protobuf:"bytes,2,rep,name=header,proto3" json:"header,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
||||
Body string `protobuf:"bytes,3,opt,name=body,proto3" json:"body,omitempty"`
|
||||
}
|
||||
|
||||
func (x *Response) Reset() {
|
||||
*x = Response{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_api_proto_api_proto_msgTypes[2]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *Response) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Response) ProtoMessage() {}
|
||||
|
||||
func (x *Response) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_api_proto_api_proto_msgTypes[2]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Response.ProtoReflect.Descriptor instead.
|
||||
func (*Response) Descriptor() ([]byte, []int) {
|
||||
return file_api_proto_api_proto_rawDescGZIP(), []int{2}
|
||||
}
|
||||
|
||||
func (x *Response) GetStatusCode() int32 {
|
||||
if x != nil {
|
||||
return x.StatusCode
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *Response) GetHeader() map[string]*Pair {
|
||||
if x != nil {
|
||||
return x.Header
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Response) GetBody() string {
|
||||
if x != nil {
|
||||
return x.Body
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// A HTTP event as RPC
|
||||
// Forwarded by the event handler
|
||||
type Event struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
// e.g login
|
||||
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
|
||||
// uuid
|
||||
Id string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"`
|
||||
// unix timestamp of event
|
||||
Timestamp int64 `protobuf:"varint,3,opt,name=timestamp,proto3" json:"timestamp,omitempty"`
|
||||
// event headers
|
||||
Header map[string]*Pair `protobuf:"bytes,4,rep,name=header,proto3" json:"header,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
||||
// the event data
|
||||
Data string `protobuf:"bytes,5,opt,name=data,proto3" json:"data,omitempty"`
|
||||
}
|
||||
|
||||
func (x *Event) Reset() {
|
||||
*x = Event{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_api_proto_api_proto_msgTypes[3]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *Event) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Event) ProtoMessage() {}
|
||||
|
||||
func (x *Event) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_api_proto_api_proto_msgTypes[3]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Event.ProtoReflect.Descriptor instead.
|
||||
func (*Event) Descriptor() ([]byte, []int) {
|
||||
return file_api_proto_api_proto_rawDescGZIP(), []int{3}
|
||||
}
|
||||
|
||||
func (x *Event) GetName() string {
|
||||
if x != nil {
|
||||
return x.Name
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Event) GetId() string {
|
||||
if x != nil {
|
||||
return x.Id
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Event) GetTimestamp() int64 {
|
||||
if x != nil {
|
||||
return x.Timestamp
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *Event) GetHeader() map[string]*Pair {
|
||||
if x != nil {
|
||||
return x.Header
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Event) GetData() string {
|
||||
if x != nil {
|
||||
return x.Data
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
var File_api_proto_api_proto protoreflect.FileDescriptor
|
||||
|
||||
var file_api_proto_api_proto_rawDesc = []byte{
|
||||
0x0a, 0x13, 0x61, 0x70, 0x69, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x61, 0x70, 0x69, 0x2e,
|
||||
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x06, 0x67, 0x6f, 0x2e, 0x61, 0x70, 0x69, 0x22, 0x30, 0x0a,
|
||||
0x04, 0x50, 0x61, 0x69, 0x72, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01,
|
||||
0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x16, 0x0a, 0x06, 0x76, 0x61, 0x6c, 0x75, 0x65,
|
||||
0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, 0x06, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x73, 0x22,
|
||||
0xc1, 0x03, 0x0a, 0x07, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x6d,
|
||||
0x65, 0x74, 0x68, 0x6f, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x6d, 0x65, 0x74,
|
||||
0x68, 0x6f, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x70, 0x61, 0x74, 0x68, 0x18, 0x02, 0x20, 0x01, 0x28,
|
||||
0x09, 0x52, 0x04, 0x70, 0x61, 0x74, 0x68, 0x12, 0x33, 0x0a, 0x06, 0x68, 0x65, 0x61, 0x64, 0x65,
|
||||
0x72, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x67, 0x6f, 0x2e, 0x61, 0x70, 0x69,
|
||||
0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x45,
|
||||
0x6e, 0x74, 0x72, 0x79, 0x52, 0x06, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x12, 0x2a, 0x0a, 0x03,
|
||||
0x67, 0x65, 0x74, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x18, 0x2e, 0x67, 0x6f, 0x2e, 0x61,
|
||||
0x70, 0x69, 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x47, 0x65, 0x74, 0x45, 0x6e,
|
||||
0x74, 0x72, 0x79, 0x52, 0x03, 0x67, 0x65, 0x74, 0x12, 0x2d, 0x0a, 0x04, 0x70, 0x6f, 0x73, 0x74,
|
||||
0x18, 0x05, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x2e, 0x61, 0x70, 0x69, 0x2e,
|
||||
0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x50, 0x6f, 0x73, 0x74, 0x45, 0x6e, 0x74, 0x72,
|
||||
0x79, 0x52, 0x04, 0x70, 0x6f, 0x73, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x62, 0x6f, 0x64, 0x79, 0x18,
|
||||
0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x62, 0x6f, 0x64, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x75,
|
||||
0x72, 0x6c, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x75, 0x72, 0x6c, 0x1a, 0x47, 0x0a,
|
||||
0x0b, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03,
|
||||
0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x22,
|
||||
0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0c, 0x2e,
|
||||
0x67, 0x6f, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x50, 0x61, 0x69, 0x72, 0x52, 0x05, 0x76, 0x61, 0x6c,
|
||||
0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x1a, 0x44, 0x0a, 0x08, 0x47, 0x65, 0x74, 0x45, 0x6e, 0x74,
|
||||
0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52,
|
||||
0x03, 0x6b, 0x65, 0x79, 0x12, 0x22, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20,
|
||||
0x01, 0x28, 0x0b, 0x32, 0x0c, 0x2e, 0x67, 0x6f, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x50, 0x61, 0x69,
|
||||
0x72, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x1a, 0x45, 0x0a, 0x09,
|
||||
0x50, 0x6f, 0x73, 0x74, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79,
|
||||
0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x22, 0x0a, 0x05, 0x76,
|
||||
0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0c, 0x2e, 0x67, 0x6f, 0x2e,
|
||||
0x61, 0x70, 0x69, 0x2e, 0x50, 0x61, 0x69, 0x72, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a,
|
||||
0x02, 0x38, 0x01, 0x22, 0xbd, 0x01, 0x0a, 0x08, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65,
|
||||
0x12, 0x1e, 0x0a, 0x0a, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x43, 0x6f, 0x64, 0x65, 0x18, 0x01,
|
||||
0x20, 0x01, 0x28, 0x05, 0x52, 0x0a, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x43, 0x6f, 0x64, 0x65,
|
||||
0x12, 0x34, 0x0a, 0x06, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b,
|
||||
0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e,
|
||||
0x73, 0x65, 0x2e, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x06,
|
||||
0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x12, 0x12, 0x0a, 0x04, 0x62, 0x6f, 0x64, 0x79, 0x18, 0x03,
|
||||
0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x62, 0x6f, 0x64, 0x79, 0x1a, 0x47, 0x0a, 0x0b, 0x48, 0x65,
|
||||
0x61, 0x64, 0x65, 0x72, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79,
|
||||
0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x22, 0x0a, 0x05, 0x76,
|
||||
0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0c, 0x2e, 0x67, 0x6f, 0x2e,
|
||||
0x61, 0x70, 0x69, 0x2e, 0x50, 0x61, 0x69, 0x72, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a,
|
||||
0x02, 0x38, 0x01, 0x22, 0xd9, 0x01, 0x0a, 0x05, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x12, 0x12, 0x0a,
|
||||
0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d,
|
||||
0x65, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69,
|
||||
0x64, 0x12, 0x1c, 0x0a, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x03,
|
||||
0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x12,
|
||||
0x31, 0x0a, 0x06, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32,
|
||||
0x19, 0x2e, 0x67, 0x6f, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x2e, 0x48,
|
||||
0x65, 0x61, 0x64, 0x65, 0x72, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x06, 0x68, 0x65, 0x61, 0x64,
|
||||
0x65, 0x72, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09,
|
||||
0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x1a, 0x47, 0x0a, 0x0b, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72,
|
||||
0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01,
|
||||
0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x22, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65,
|
||||
0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0c, 0x2e, 0x67, 0x6f, 0x2e, 0x61, 0x70, 0x69, 0x2e,
|
||||
0x50, 0x61, 0x69, 0x72, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x62,
|
||||
0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
|
||||
}
|
||||
|
||||
var (
|
||||
file_api_proto_api_proto_rawDescOnce sync.Once
|
||||
file_api_proto_api_proto_rawDescData = file_api_proto_api_proto_rawDesc
|
||||
)
|
||||
|
||||
func file_api_proto_api_proto_rawDescGZIP() []byte {
|
||||
file_api_proto_api_proto_rawDescOnce.Do(func() {
|
||||
file_api_proto_api_proto_rawDescData = protoimpl.X.CompressGZIP(file_api_proto_api_proto_rawDescData)
|
||||
})
|
||||
return file_api_proto_api_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_api_proto_api_proto_msgTypes = make([]protoimpl.MessageInfo, 9)
|
||||
var file_api_proto_api_proto_goTypes = []interface{}{
|
||||
(*Pair)(nil), // 0: go.api.Pair
|
||||
(*Request)(nil), // 1: go.api.Request
|
||||
(*Response)(nil), // 2: go.api.Response
|
||||
(*Event)(nil), // 3: go.api.Event
|
||||
nil, // 4: go.api.Request.HeaderEntry
|
||||
nil, // 5: go.api.Request.GetEntry
|
||||
nil, // 6: go.api.Request.PostEntry
|
||||
nil, // 7: go.api.Response.HeaderEntry
|
||||
nil, // 8: go.api.Event.HeaderEntry
|
||||
}
|
||||
var file_api_proto_api_proto_depIdxs = []int32{
|
||||
4, // 0: go.api.Request.header:type_name -> go.api.Request.HeaderEntry
|
||||
5, // 1: go.api.Request.get:type_name -> go.api.Request.GetEntry
|
||||
6, // 2: go.api.Request.post:type_name -> go.api.Request.PostEntry
|
||||
7, // 3: go.api.Response.header:type_name -> go.api.Response.HeaderEntry
|
||||
8, // 4: go.api.Event.header:type_name -> go.api.Event.HeaderEntry
|
||||
0, // 5: go.api.Request.HeaderEntry.value:type_name -> go.api.Pair
|
||||
0, // 6: go.api.Request.GetEntry.value:type_name -> go.api.Pair
|
||||
0, // 7: go.api.Request.PostEntry.value:type_name -> go.api.Pair
|
||||
0, // 8: go.api.Response.HeaderEntry.value:type_name -> go.api.Pair
|
||||
0, // 9: go.api.Event.HeaderEntry.value:type_name -> go.api.Pair
|
||||
10, // [10:10] is the sub-list for method output_type
|
||||
10, // [10:10] is the sub-list for method input_type
|
||||
10, // [10:10] is the sub-list for extension type_name
|
||||
10, // [10:10] is the sub-list for extension extendee
|
||||
0, // [0:10] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_api_proto_api_proto_init() }
|
||||
func file_api_proto_api_proto_init() {
|
||||
if File_api_proto_api_proto != nil {
|
||||
return
|
||||
}
|
||||
if !protoimpl.UnsafeEnabled {
|
||||
file_api_proto_api_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*Pair); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
file_api_proto_api_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*Request); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
file_api_proto_api_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*Response); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
file_api_proto_api_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*Event); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: file_api_proto_api_proto_rawDesc,
|
||||
NumEnums: 0,
|
||||
NumMessages: 9,
|
||||
NumExtensions: 0,
|
||||
NumServices: 0,
|
||||
},
|
||||
GoTypes: file_api_proto_api_proto_goTypes,
|
||||
DependencyIndexes: file_api_proto_api_proto_depIdxs,
|
||||
MessageInfos: file_api_proto_api_proto_msgTypes,
|
||||
}.Build()
|
||||
File_api_proto_api_proto = out.File
|
||||
file_api_proto_api_proto_rawDesc = nil
|
||||
file_api_proto_api_proto_goTypes = nil
|
||||
file_api_proto_api_proto_depIdxs = nil
|
||||
}
|
@@ -1,21 +0,0 @@
|
||||
// Code generated by protoc-gen-micro. DO NOT EDIT.
|
||||
// source: api/proto/api.proto
|
||||
|
||||
package go_api
|
||||
|
||||
import (
|
||||
fmt "fmt"
|
||||
proto "github.com/golang/protobuf/proto"
|
||||
math "math"
|
||||
)
|
||||
|
||||
// Reference imports to suppress errors if they are not otherwise used.
|
||||
var _ = proto.Marshal
|
||||
var _ = fmt.Errorf
|
||||
var _ = math.Inf
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the proto package it is being compiled against.
|
||||
// A compilation error at this line likely means your copy of the
|
||||
// proto package needs to be updated.
|
||||
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
|
@@ -1,43 +0,0 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package go.api;
|
||||
|
||||
message Pair {
|
||||
string key = 1;
|
||||
repeated string values = 2;
|
||||
}
|
||||
|
||||
// A HTTP request as RPC
|
||||
// Forward by the api handler
|
||||
message Request {
|
||||
string method = 1;
|
||||
string path = 2;
|
||||
map<string, Pair> header = 3;
|
||||
map<string, Pair> get = 4;
|
||||
map<string, Pair> post = 5;
|
||||
string body = 6; // raw request body; if not application/x-www-form-urlencoded
|
||||
string url = 7;
|
||||
}
|
||||
|
||||
// A HTTP response as RPC
|
||||
// Expected response for the api handler
|
||||
message Response {
|
||||
int32 statusCode = 1;
|
||||
map<string, Pair> header = 2;
|
||||
string body = 3;
|
||||
}
|
||||
|
||||
// A HTTP event as RPC
|
||||
// Forwarded by the event handler
|
||||
message Event {
|
||||
// e.g login
|
||||
string name = 1;
|
||||
// uuid
|
||||
string id = 2;
|
||||
// unix timestamp of event
|
||||
int64 timestamp = 3;
|
||||
// event headers
|
||||
map<string, Pair> header = 4;
|
||||
// the event data
|
||||
string data = 5;
|
||||
}
|
@@ -1,12 +1,12 @@
|
||||
// Package grpc resolves a grpc service like /greeter.Say/Hello to greeter service
|
||||
package grpc
|
||||
package grpc // import "go.unistack.org/micro/v3/api/resolver/grpc"
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/unistack-org/micro/v3/api/resolver"
|
||||
"go.unistack.org/micro/v3/api/resolver"
|
||||
)
|
||||
|
||||
// Resolver struct
|
||||
|
@@ -1,17 +1,18 @@
|
||||
// Package host resolves using http host
|
||||
package host
|
||||
package host // import "go.unistack.org/micro/v3/api/resolver/host"
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/unistack-org/micro/v3/api/resolver"
|
||||
"go.unistack.org/micro/v3/api/resolver"
|
||||
)
|
||||
|
||||
type Resolver struct {
|
||||
type hostResolver struct {
|
||||
opts resolver.Options
|
||||
}
|
||||
|
||||
func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) {
|
||||
// Resolve endpoint
|
||||
func (r *hostResolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) {
|
||||
// parse options
|
||||
options := resolver.NewResolveOptions(opts...)
|
||||
|
||||
@@ -24,10 +25,11 @@ func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *Resolver) String() string {
|
||||
func (r *hostResolver) String() string {
|
||||
return "host"
|
||||
}
|
||||
|
||||
// NewResolver creates new host api resolver
|
||||
func NewResolver(opts ...resolver.Option) resolver.Resolver {
|
||||
return &Resolver{opts: resolver.NewOptions(opts...)}
|
||||
return &hostResolver{opts: resolver.NewOptions(opts...)}
|
||||
}
|
||||
|
@@ -3,14 +3,17 @@ package resolver
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/unistack-org/micro/v3/register"
|
||||
"go.unistack.org/micro/v3/register"
|
||||
)
|
||||
|
||||
// Options struct
|
||||
type Options struct {
|
||||
Handler string
|
||||
// Context is for external defined options
|
||||
Context context.Context
|
||||
// Handler name
|
||||
Handler string
|
||||
// ServicePrefix is the prefix
|
||||
ServicePrefix string
|
||||
Context context.Context
|
||||
}
|
||||
|
||||
// Option func
|
||||
|
@@ -1,17 +1,19 @@
|
||||
// Package path resolves using http path
|
||||
package path
|
||||
package path // import "go.unistack.org/micro/v3/api/resolver/path"
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/unistack-org/micro/v3/api/resolver"
|
||||
"go.unistack.org/micro/v3/api/resolver"
|
||||
)
|
||||
|
||||
// Resolver the path resolver
|
||||
type Resolver struct {
|
||||
opts resolver.Options
|
||||
}
|
||||
|
||||
// Resolve resolves endpoint
|
||||
func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) {
|
||||
// parse options
|
||||
options := resolver.NewResolveOptions(opts...)
|
||||
@@ -31,10 +33,12 @@ func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*
|
||||
}, nil
|
||||
}
|
||||
|
||||
// String retruns the string representation
|
||||
func (r *Resolver) String() string {
|
||||
return "path"
|
||||
}
|
||||
|
||||
// NewResolver returns new path resolver
|
||||
func NewResolver(opts ...resolver.Option) resolver.Resolver {
|
||||
return &Resolver{opts: resolver.NewOptions(opts...)}
|
||||
}
|
||||
|
@@ -1,5 +1,5 @@
|
||||
// Package resolver resolves a http request to an endpoint
|
||||
package resolver
|
||||
package resolver // import "go.unistack.org/micro/v3/api/resolver"
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
@@ -1,28 +1,30 @@
|
||||
// Package subdomain is a resolver which uses the subdomain to determine the domain to route to. It
|
||||
// offloads the endpoint resolution to a child resolver which is provided in New.
|
||||
package subdomain
|
||||
package subdomain // import "go.unistack.org/micro/v3/api/resolver/subdomain"
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/unistack-org/micro/v3/api/resolver"
|
||||
"github.com/unistack-org/micro/v3/logger"
|
||||
"go.unistack.org/micro/v3/api/resolver"
|
||||
"go.unistack.org/micro/v3/logger"
|
||||
"golang.org/x/net/publicsuffix"
|
||||
)
|
||||
|
||||
// NewResolver creates new subdomain api resolver
|
||||
func NewResolver(parent resolver.Resolver, opts ...resolver.Option) resolver.Resolver {
|
||||
options := resolver.NewOptions(opts...)
|
||||
return &Resolver{options, parent}
|
||||
return &subdomainResolver{opts: options, Resolver: parent}
|
||||
}
|
||||
|
||||
type Resolver struct {
|
||||
opts resolver.Options
|
||||
type subdomainResolver struct {
|
||||
resolver.Resolver
|
||||
opts resolver.Options
|
||||
}
|
||||
|
||||
func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) {
|
||||
// Resolve resolve endpoint based on subdomain
|
||||
func (r *subdomainResolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) {
|
||||
if dom := r.Domain(req); len(dom) > 0 {
|
||||
opts = append(opts, resolver.Domain(dom))
|
||||
}
|
||||
@@ -30,7 +32,8 @@ func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*
|
||||
return r.Resolver.Resolve(req, opts...)
|
||||
}
|
||||
|
||||
func (r *Resolver) Domain(req *http.Request) string {
|
||||
// Domain returns domain
|
||||
func (r *subdomainResolver) Domain(req *http.Request) string {
|
||||
// determine the host, e.g. foobar.m3o.app
|
||||
host := req.URL.Hostname()
|
||||
if len(host) == 0 {
|
||||
@@ -82,6 +85,6 @@ func (r *Resolver) Domain(req *http.Request) string {
|
||||
return strings.Join(comps, "-")
|
||||
}
|
||||
|
||||
func (r *Resolver) String() string {
|
||||
func (r *subdomainResolver) String() string {
|
||||
return "subdomain"
|
||||
}
|
||||
|
@@ -5,9 +5,7 @@ import (
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/unistack-org/micro/v3/api/resolver/vpath"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"go.unistack.org/micro/v3/api/resolver/vpath"
|
||||
)
|
||||
|
||||
func TestResolve(t *testing.T) {
|
||||
@@ -62,9 +60,13 @@ func TestResolve(t *testing.T) {
|
||||
t.Run(tc.Name, func(t *testing.T) {
|
||||
r := NewResolver(vpath.NewResolver())
|
||||
result, err := r.Resolve(&http.Request{URL: &url.URL{Host: tc.Host, Path: "foo/bar"}})
|
||||
assert.Nil(t, err, "Expecter err to be nil")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result != nil {
|
||||
assert.Equal(t, tc.Result, result.Domain, "Expected %v but got %v", tc.Result, result.Domain)
|
||||
if tc.Result != result.Domain {
|
||||
t.Fatalf("Expected %v but got %v", tc.Result, result.Domain)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
@@ -1,5 +1,5 @@
|
||||
// Package vpath resolves using http path and recognised versioned urls
|
||||
package vpath
|
||||
package vpath // import "go.unistack.org/micro/v3/api/resolver/vpath"
|
||||
|
||||
import (
|
||||
"errors"
|
||||
@@ -7,22 +7,22 @@ import (
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/unistack-org/micro/v3/api/resolver"
|
||||
"go.unistack.org/micro/v3/api/resolver"
|
||||
)
|
||||
|
||||
// NewResolver creates new vpath api resolver
|
||||
func NewResolver(opts ...resolver.Option) resolver.Resolver {
|
||||
return &Resolver{opts: resolver.NewOptions(opts...)}
|
||||
return &vpathResolver{opts: resolver.NewOptions(opts...)}
|
||||
}
|
||||
|
||||
type Resolver struct {
|
||||
type vpathResolver struct {
|
||||
opts resolver.Options
|
||||
}
|
||||
|
||||
var (
|
||||
re = regexp.MustCompile("^v[0-9]+$")
|
||||
)
|
||||
var re = regexp.MustCompile("^v[0-9]+$")
|
||||
|
||||
func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) {
|
||||
// Resolve endpoint
|
||||
func (r *vpathResolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) {
|
||||
if req.URL.Path == "/" {
|
||||
return nil, errors.New("unknown name")
|
||||
}
|
||||
@@ -60,12 +60,12 @@ func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *Resolver) String() string {
|
||||
return "path"
|
||||
func (r *vpathResolver) String() string {
|
||||
return "vpath"
|
||||
}
|
||||
|
||||
// withPrefix transforms "foo" into "go.micro.api.foo"
|
||||
func (r *Resolver) withPrefix(parts ...string) string {
|
||||
func (r *vpathResolver) withPrefix(parts ...string) string {
|
||||
p := r.opts.ServicePrefix
|
||||
if len(p) > 0 {
|
||||
parts = append([]string{p}, parts...)
|
||||
|
@@ -3,22 +3,30 @@ package router
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/unistack-org/micro/v3/api/resolver"
|
||||
"github.com/unistack-org/micro/v3/api/resolver/vpath"
|
||||
"github.com/unistack-org/micro/v3/logger"
|
||||
"github.com/unistack-org/micro/v3/register"
|
||||
"go.unistack.org/micro/v3/api/resolver"
|
||||
"go.unistack.org/micro/v3/api/resolver/vpath"
|
||||
"go.unistack.org/micro/v3/logger"
|
||||
"go.unistack.org/micro/v3/register"
|
||||
)
|
||||
|
||||
// Options holds the options for api router
|
||||
type Options struct {
|
||||
Handler string
|
||||
// Register for service lookup
|
||||
Register register.Register
|
||||
// Resolver to use
|
||||
Resolver resolver.Resolver
|
||||
Logger logger.Logger
|
||||
Context context.Context
|
||||
// Logger micro logger
|
||||
Logger logger.Logger
|
||||
// Context is for external options
|
||||
Context context.Context
|
||||
// Handler name
|
||||
Handler string
|
||||
}
|
||||
|
||||
// Option func signature
|
||||
type Option func(o *Options)
|
||||
|
||||
// NewOptions returns options struct filled by opts
|
||||
func NewOptions(opts ...Option) Options {
|
||||
options := Options{
|
||||
Context: context.Background(),
|
||||
|
@@ -1,12 +1,15 @@
|
||||
// Package router provides api service routing
|
||||
package router
|
||||
package router // import "go.unistack.org/micro/v3/api/router"
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/unistack-org/micro/v3/api"
|
||||
"go.unistack.org/micro/v3/api"
|
||||
)
|
||||
|
||||
// DefaultRouter contains default router implementation
|
||||
var DefaultRouter Router
|
||||
|
||||
// Router is used to determine an endpoint for a request
|
||||
type Router interface {
|
||||
// Returns options
|
||||
@@ -23,6 +26,6 @@ type Router interface {
|
||||
Deregister(ep *api.Endpoint) error
|
||||
// Route returns an api.Service route
|
||||
Route(r *http.Request) (*api.Service, error)
|
||||
// String represenation of router
|
||||
// String representation of router
|
||||
String() string
|
||||
}
|
||||
|
41
auth/auth.go
41
auth/auth.go
@@ -1,12 +1,12 @@
|
||||
// Package auth provides authentication and authorization capability
|
||||
package auth
|
||||
package auth // import "go.unistack.org/micro/v3/auth"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/unistack-org/micro/v3/metadata"
|
||||
"go.unistack.org/micro/v3/metadata"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -19,6 +19,7 @@ const (
|
||||
)
|
||||
|
||||
var (
|
||||
// DefaultAuth holds default auth implementation
|
||||
DefaultAuth Auth = NewAuth()
|
||||
// ErrInvalidToken is when the token provided is not valid
|
||||
ErrInvalidToken = errors.New("invalid token provided")
|
||||
@@ -29,7 +30,7 @@ var (
|
||||
// Auth provides authentication and authorization
|
||||
type Auth interface {
|
||||
// Init the auth
|
||||
Init(opts ...Option)
|
||||
Init(opts ...Option) error
|
||||
// Options set for auth
|
||||
Options() Options
|
||||
// Generate a new account
|
||||
@@ -52,30 +53,30 @@ type Auth interface {
|
||||
|
||||
// Account provided by an auth provider
|
||||
type Account struct {
|
||||
// ID of the account e.g. email
|
||||
// Metadata any other associated metadata
|
||||
Metadata metadata.Metadata `json:"metadata"`
|
||||
// ID of the account e.g. email or id
|
||||
ID string `json:"id"`
|
||||
// Type of the account, e.g. service
|
||||
Type string `json:"type"`
|
||||
// Issuer of the account
|
||||
Issuer string `json:"issuer"`
|
||||
// Any other associated metadata
|
||||
Metadata metadata.Metadata `json:"metadata"`
|
||||
// Scopes the account has access to
|
||||
Scopes []string `json:"scopes"`
|
||||
// Secret for the account, e.g. the password
|
||||
Secret string `json:"secret"`
|
||||
// Scopes the account has access to
|
||||
Scopes []string `json:"scopes"`
|
||||
}
|
||||
|
||||
// Token can be short or long lived
|
||||
type Token struct {
|
||||
// The token to be used for accessing resources
|
||||
AccessToken string `json:"access_token"`
|
||||
// RefreshToken to be used to generate a new token
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
// Time of token creation
|
||||
Created time.Time `json:"created"`
|
||||
// Time of token expiry
|
||||
Expiry time.Time `json:"expiry"`
|
||||
// The token to be used for accessing resources
|
||||
AccessToken string `json:"access_token"`
|
||||
// RefreshToken to be used to generate a new token
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
}
|
||||
|
||||
// Expired returns a boolean indicating if the token needs to be refreshed
|
||||
@@ -105,17 +106,15 @@ const (
|
||||
|
||||
// Rule is used to verify access to a resource
|
||||
type Rule struct {
|
||||
// ID of the rule, e.g. "public"
|
||||
ID string
|
||||
// Scope the rule requires, a blank scope indicates open to the public and * indicates the rule
|
||||
// applies to any valid account
|
||||
Scope string
|
||||
// Resource the rule applies to
|
||||
// Resource that rule belongs to
|
||||
Resource *Resource
|
||||
// Access determines if the rule grants or denies access to the resource
|
||||
// ID of the rule
|
||||
ID string
|
||||
// Scope of the rule
|
||||
Scope string
|
||||
// Access flag allow/deny
|
||||
Access Access
|
||||
// Priority the rule should take when verifying a request, the higher the value the sooner the
|
||||
// rule will be applied
|
||||
// Priority holds the rule priority
|
||||
Priority int32
|
||||
}
|
||||
|
||||
|
@@ -1,7 +1,7 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
"go.unistack.org/micro/v3/util/id"
|
||||
)
|
||||
|
||||
type noopAuth struct {
|
||||
@@ -14,10 +14,11 @@ func (n *noopAuth) String() string {
|
||||
}
|
||||
|
||||
// Init the auth
|
||||
func (n *noopAuth) Init(opts ...Option) {
|
||||
func (n *noopAuth) Init(opts ...Option) error {
|
||||
for _, o := range opts {
|
||||
o(&n.opts)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Options set for auth
|
||||
@@ -60,11 +61,11 @@ func (n *noopAuth) Verify(acc *Account, res *Resource, opts ...VerifyOption) err
|
||||
|
||||
// Inspect a token
|
||||
func (n *noopAuth) Inspect(token string) (*Account, error) {
|
||||
uid, err := uuid.NewRandom()
|
||||
id, err := id.New()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Account{ID: uid.String(), Issuer: n.Options().Issuer}, nil
|
||||
return &Account{ID: id, Issuer: n.Options().Issuer}, nil
|
||||
}
|
||||
|
||||
// Token generation using an account id and secret
|
||||
|
@@ -4,11 +4,11 @@ import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/unistack-org/micro/v3/logger"
|
||||
"github.com/unistack-org/micro/v3/metadata"
|
||||
"github.com/unistack-org/micro/v3/meter"
|
||||
"github.com/unistack-org/micro/v3/store"
|
||||
"github.com/unistack-org/micro/v3/tracer"
|
||||
"go.unistack.org/micro/v3/logger"
|
||||
"go.unistack.org/micro/v3/metadata"
|
||||
"go.unistack.org/micro/v3/meter"
|
||||
"go.unistack.org/micro/v3/store"
|
||||
"go.unistack.org/micro/v3/tracer"
|
||||
)
|
||||
|
||||
// NewOptions creates Options struct from slice of options
|
||||
@@ -24,34 +24,36 @@ func NewOptions(opts ...Option) Options {
|
||||
return options
|
||||
}
|
||||
|
||||
// Options struct holds auth options
|
||||
type Options struct {
|
||||
Name string
|
||||
// Issuer of the service's account
|
||||
Issuer string
|
||||
// ID is the services auth ID
|
||||
ID string
|
||||
// Secret is used to authenticate the service
|
||||
Secret string
|
||||
// Context holds the external options
|
||||
Context context.Context
|
||||
// Meter used for metrics
|
||||
Meter meter.Meter
|
||||
// Logger used for logging
|
||||
Logger logger.Logger
|
||||
// Tracer used for tracing
|
||||
Tracer tracer.Tracer
|
||||
// Store used for stre data
|
||||
Store store.Store
|
||||
// Token is the services token used to authenticate itself
|
||||
Token *Token
|
||||
// PublicKey for decoding JWTs
|
||||
PublicKey string
|
||||
// PrivateKey for encoding JWTs
|
||||
PrivateKey string
|
||||
// LoginURL is the relative url path where a user can login
|
||||
LoginURL string
|
||||
// Store to back auth
|
||||
Store store.Store
|
||||
// PrivateKey for encoding JWTs
|
||||
PrivateKey string
|
||||
// PublicKey for decoding JWTs
|
||||
PublicKey string
|
||||
// Secret is used to authenticate the service
|
||||
Secret string
|
||||
// ID is the services auth ID
|
||||
ID string
|
||||
// Issuer of the service's account
|
||||
Issuer string
|
||||
// Name holds the auth name
|
||||
Name string
|
||||
// Addrs sets the addresses of auth
|
||||
Addrs []string
|
||||
// Logger sets the logger
|
||||
Logger logger.Logger
|
||||
// Meter sets tht meter
|
||||
Meter meter.Meter
|
||||
// Tracer
|
||||
Tracer tracer.Tracer
|
||||
// Context to store other options
|
||||
Context context.Context
|
||||
}
|
||||
|
||||
// Option func
|
||||
@@ -123,18 +125,12 @@ func LoginURL(url string) Option {
|
||||
|
||||
// GenerateOptions struct
|
||||
type GenerateOptions struct {
|
||||
// Metadata associated with the account
|
||||
Metadata metadata.Metadata
|
||||
// Scopes the account has access too
|
||||
Scopes []string
|
||||
// Provider of the account, e.g. oauth
|
||||
Provider string
|
||||
// Type of the account, e.g. user
|
||||
Type string
|
||||
// Secret used to authenticate the account
|
||||
Secret string
|
||||
// Issuer of the account, e.g. micro
|
||||
Issuer string
|
||||
Type string
|
||||
Secret string
|
||||
Issuer string
|
||||
Scopes []string
|
||||
}
|
||||
|
||||
// GenerateOption func
|
||||
@@ -193,16 +189,11 @@ func NewGenerateOptions(opts ...GenerateOption) GenerateOptions {
|
||||
|
||||
// TokenOptions struct
|
||||
type TokenOptions struct {
|
||||
// ID for the account
|
||||
ID string
|
||||
// Secret for the account
|
||||
Secret string
|
||||
// RefreshToken is used to refesh a token
|
||||
ID string
|
||||
Secret string
|
||||
RefreshToken string
|
||||
// Expiry is the time the token should live for
|
||||
Expiry time.Duration
|
||||
// Issuer of the account
|
||||
Issuer string
|
||||
Issuer string
|
||||
Expiry time.Duration
|
||||
}
|
||||
|
||||
// TokenOption func
|
||||
|
@@ -9,6 +9,7 @@ import (
|
||||
// VerifyAccess an account has access to a resource using the rules provided. If the account does not have
|
||||
// access an error will be returned. If there are no rules provided which match the resource, an error
|
||||
// will be returned
|
||||
//nolint:gocyclo
|
||||
func VerifyAccess(rules []*Rule, acc *Account, res *Resource) error {
|
||||
// the rule is only to be applied if the type matches the resource or is catch-all (*)
|
||||
validTypes := []string{"*", res.Type}
|
||||
|
@@ -24,11 +24,11 @@ func TestVerify(t *testing.T) {
|
||||
}
|
||||
|
||||
tt := []struct {
|
||||
Name string
|
||||
Rules []*Rule
|
||||
Error error
|
||||
Account *Account
|
||||
Resource *Resource
|
||||
Error error
|
||||
Name string
|
||||
Rules []*Rule
|
||||
}{
|
||||
{
|
||||
Name: "NoRules",
|
||||
|
104
broker/broker.go
104
broker/broker.go
@@ -1,50 +1,130 @@
|
||||
// Package broker is an interface used for asynchronous messaging
|
||||
package broker
|
||||
package broker // import "go.unistack.org/micro/v3/broker"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/unistack-org/micro/v3/metadata"
|
||||
"go.unistack.org/micro/v3/metadata"
|
||||
)
|
||||
|
||||
// DefaultBroker default memory broker
|
||||
var DefaultBroker Broker = NewBroker()
|
||||
|
||||
var (
|
||||
// DefaultBroker default broker
|
||||
DefaultBroker Broker = NewBroker()
|
||||
// ErrNotConnected returns when broker used but not connected yet
|
||||
ErrNotConnected = errors.New("broker not connected")
|
||||
// ErrDisconnected returns when broker disconnected
|
||||
ErrDisconnected = errors.New("broker disconnected")
|
||||
)
|
||||
|
||||
// Broker is an interface used for asynchronous messaging.
|
||||
type Broker interface {
|
||||
// Name returns broker instance name
|
||||
Name() string
|
||||
Init(...Option) error
|
||||
// Init initilize broker
|
||||
Init(opts ...Option) error
|
||||
// Options returns broker options
|
||||
Options() Options
|
||||
// Address return configured address
|
||||
Address() string
|
||||
Connect(context.Context) error
|
||||
Disconnect(context.Context) error
|
||||
Publish(context.Context, string, *Message, ...PublishOption) error
|
||||
Subscribe(context.Context, string, Handler, ...SubscribeOption) (Subscriber, error)
|
||||
// Connect connects to broker
|
||||
Connect(ctx context.Context) error
|
||||
// Disconnect disconnect from broker
|
||||
Disconnect(ctx context.Context) error
|
||||
// Publish message to broker topic
|
||||
Publish(ctx context.Context, topic string, msg *Message, opts ...PublishOption) error
|
||||
// Subscribe subscribes to topic message via handler
|
||||
Subscribe(ctx context.Context, topic string, h Handler, opts ...SubscribeOption) (Subscriber, error)
|
||||
// BatchPublish messages to broker with multiple topics
|
||||
BatchPublish(ctx context.Context, msgs []*Message, opts ...PublishOption) error
|
||||
// BatchSubscribe subscribes to topic messages via handler
|
||||
BatchSubscribe(ctx context.Context, topic string, h BatchHandler, opts ...SubscribeOption) (Subscriber, error)
|
||||
// String type of broker
|
||||
String() string
|
||||
}
|
||||
|
||||
// Handler is used to process messages via a subscription of a topic.
|
||||
type Handler func(Event) error
|
||||
|
||||
// Events contains multiple events
|
||||
type Events []Event
|
||||
|
||||
func (evs Events) Ack() error {
|
||||
var err error
|
||||
for _, ev := range evs {
|
||||
if err = ev.Ack(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (evs Events) SetError(err error) {
|
||||
for _, ev := range evs {
|
||||
ev.SetError(err)
|
||||
}
|
||||
}
|
||||
|
||||
// BatchHandler is used to process messages in batches via a subscription of a topic.
|
||||
type BatchHandler func(Events) error
|
||||
|
||||
// Event is given to a subscription handler for processing
|
||||
type Event interface {
|
||||
// Topic returns event topic
|
||||
Topic() string
|
||||
// Message returns broker message
|
||||
Message() *Message
|
||||
// Ack acknowledge message
|
||||
Ack() error
|
||||
// Error returns message error (like decoding errors or some other)
|
||||
Error() error
|
||||
// SetError set event processing error
|
||||
SetError(err error)
|
||||
}
|
||||
|
||||
// RawMessage is a raw encoded JSON value.
|
||||
// It implements Marshaler and Unmarshaler and can be used to delay decoding or precompute a encoding.
|
||||
type RawMessage []byte
|
||||
|
||||
// MarshalJSON returns m as the JSON encoding of m.
|
||||
func (m *RawMessage) MarshalJSON() ([]byte, error) {
|
||||
if m == nil {
|
||||
return []byte("null"), nil
|
||||
}
|
||||
return *m, nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON sets *m to a copy of data.
|
||||
func (m *RawMessage) UnmarshalJSON(data []byte) error {
|
||||
if m == nil {
|
||||
return errors.New("RawMessage UnmarshalJSON on nil pointer")
|
||||
}
|
||||
*m = append((*m)[0:0], data...)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Message is used to transfer data
|
||||
type Message struct {
|
||||
Header metadata.Metadata // contains message metadata
|
||||
Body []byte // contains message body
|
||||
// Header contains message metadata
|
||||
Header metadata.Metadata
|
||||
// Body contains message body
|
||||
Body RawMessage
|
||||
}
|
||||
|
||||
// NewMessage create broker message with topic filled
|
||||
func NewMessage(topic string) *Message {
|
||||
m := &Message{Header: metadata.New(2)}
|
||||
m.Header.Set(metadata.HeaderTopic, topic)
|
||||
return m
|
||||
}
|
||||
|
||||
// Subscriber is a convenience return type for the Subscribe method
|
||||
type Subscriber interface {
|
||||
// Options returns subscriber options
|
||||
Options() SubscribeOptions
|
||||
// Topic returns topic for subscription
|
||||
Topic() string
|
||||
Unsubscribe(context.Context) error
|
||||
// Unsubscribe from topic
|
||||
Unsubscribe(ctx context.Context) error
|
||||
}
|
||||
|
342
broker/memory.go
Normal file
342
broker/memory.go
Normal file
@@ -0,0 +1,342 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
"go.unistack.org/micro/v3/logger"
|
||||
"go.unistack.org/micro/v3/metadata"
|
||||
maddr "go.unistack.org/micro/v3/util/addr"
|
||||
"go.unistack.org/micro/v3/util/id"
|
||||
mnet "go.unistack.org/micro/v3/util/net"
|
||||
"go.unistack.org/micro/v3/util/rand"
|
||||
)
|
||||
|
||||
type memoryBroker struct {
|
||||
subscribers map[string][]*memorySubscriber
|
||||
addr string
|
||||
opts Options
|
||||
sync.RWMutex
|
||||
connected bool
|
||||
}
|
||||
|
||||
type memoryEvent struct {
|
||||
err error
|
||||
message interface{}
|
||||
topic string
|
||||
opts Options
|
||||
}
|
||||
|
||||
type memorySubscriber struct {
|
||||
ctx context.Context
|
||||
exit chan bool
|
||||
handler Handler
|
||||
batchhandler BatchHandler
|
||||
id string
|
||||
topic string
|
||||
opts SubscribeOptions
|
||||
}
|
||||
|
||||
func (m *memoryBroker) Options() Options {
|
||||
return m.opts
|
||||
}
|
||||
|
||||
func (m *memoryBroker) Address() string {
|
||||
return m.addr
|
||||
}
|
||||
|
||||
func (m *memoryBroker) Connect(ctx context.Context) error {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
|
||||
if m.connected {
|
||||
return nil
|
||||
}
|
||||
|
||||
// use 127.0.0.1 to avoid scan of all network interfaces
|
||||
addr, err := maddr.Extract("127.0.0.1")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var rng rand.Rand
|
||||
i := rng.Intn(20000)
|
||||
// set addr with port
|
||||
addr = mnet.HostPort(addr, 10000+i)
|
||||
|
||||
m.addr = addr
|
||||
m.connected = true
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memoryBroker) Disconnect(ctx context.Context) error {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
|
||||
if !m.connected {
|
||||
return nil
|
||||
}
|
||||
|
||||
m.connected = false
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memoryBroker) Init(opts ...Option) error {
|
||||
for _, o := range opts {
|
||||
o(&m.opts)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memoryBroker) Publish(ctx context.Context, topic string, msg *Message, opts ...PublishOption) error {
|
||||
msg.Header.Set(metadata.HeaderTopic, topic)
|
||||
return m.publish(ctx, []*Message{msg}, opts...)
|
||||
}
|
||||
|
||||
func (m *memoryBroker) BatchPublish(ctx context.Context, msgs []*Message, opts ...PublishOption) error {
|
||||
return m.publish(ctx, msgs, opts...)
|
||||
}
|
||||
|
||||
func (m *memoryBroker) publish(ctx context.Context, msgs []*Message, opts ...PublishOption) error {
|
||||
m.RLock()
|
||||
if !m.connected {
|
||||
m.RUnlock()
|
||||
return ErrNotConnected
|
||||
}
|
||||
m.RUnlock()
|
||||
|
||||
var err error
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
options := NewPublishOptions(opts...)
|
||||
|
||||
msgTopicMap := make(map[string]Events)
|
||||
for _, v := range msgs {
|
||||
p := &memoryEvent{opts: m.opts}
|
||||
|
||||
if m.opts.Codec == nil || options.BodyOnly {
|
||||
p.topic, _ = v.Header.Get(metadata.HeaderTopic)
|
||||
p.message = v.Body
|
||||
} else {
|
||||
p.topic, _ = v.Header.Get(metadata.HeaderTopic)
|
||||
p.message, err = m.opts.Codec.Marshal(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
msgTopicMap[p.topic] = append(msgTopicMap[p.topic], p)
|
||||
}
|
||||
|
||||
beh := m.opts.BatchErrorHandler
|
||||
eh := m.opts.ErrorHandler
|
||||
|
||||
for t, ms := range msgTopicMap {
|
||||
m.RLock()
|
||||
subs, ok := m.subscribers[t]
|
||||
m.RUnlock()
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
for _, sub := range subs {
|
||||
if sub.opts.BatchErrorHandler != nil {
|
||||
beh = sub.opts.BatchErrorHandler
|
||||
}
|
||||
if sub.opts.ErrorHandler != nil {
|
||||
eh = sub.opts.ErrorHandler
|
||||
}
|
||||
|
||||
switch {
|
||||
// batch processing
|
||||
case sub.batchhandler != nil:
|
||||
if err = sub.batchhandler(ms); err != nil {
|
||||
ms.SetError(err)
|
||||
if beh != nil {
|
||||
_ = beh(ms)
|
||||
} else if m.opts.Logger.V(logger.ErrorLevel) {
|
||||
m.opts.Logger.Error(m.opts.Context, err.Error())
|
||||
}
|
||||
} else if sub.opts.AutoAck {
|
||||
if err = ms.Ack(); err != nil {
|
||||
m.opts.Logger.Errorf(m.opts.Context, "ack failed: %v", err)
|
||||
}
|
||||
}
|
||||
// single processing
|
||||
case sub.handler != nil:
|
||||
for _, p := range ms {
|
||||
if err = sub.handler(p); err != nil {
|
||||
p.SetError(err)
|
||||
if eh != nil {
|
||||
_ = eh(p)
|
||||
} else if m.opts.Logger.V(logger.ErrorLevel) {
|
||||
m.opts.Logger.Error(m.opts.Context, err.Error())
|
||||
}
|
||||
} else if sub.opts.AutoAck {
|
||||
if err = p.Ack(); err != nil {
|
||||
m.opts.Logger.Errorf(m.opts.Context, "ack failed: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memoryBroker) BatchSubscribe(ctx context.Context, topic string, handler BatchHandler, opts ...SubscribeOption) (Subscriber, error) {
|
||||
m.RLock()
|
||||
if !m.connected {
|
||||
m.RUnlock()
|
||||
return nil, ErrNotConnected
|
||||
}
|
||||
m.RUnlock()
|
||||
|
||||
sid, err := id.New()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
options := NewSubscribeOptions(opts...)
|
||||
|
||||
sub := &memorySubscriber{
|
||||
exit: make(chan bool, 1),
|
||||
id: sid,
|
||||
topic: topic,
|
||||
batchhandler: handler,
|
||||
opts: options,
|
||||
ctx: ctx,
|
||||
}
|
||||
|
||||
m.Lock()
|
||||
m.subscribers[topic] = append(m.subscribers[topic], sub)
|
||||
m.Unlock()
|
||||
|
||||
go func() {
|
||||
<-sub.exit
|
||||
m.Lock()
|
||||
newSubscribers := make([]*memorySubscriber, 0, len(m.subscribers)-1)
|
||||
for _, sb := range m.subscribers[topic] {
|
||||
if sb.id == sub.id {
|
||||
continue
|
||||
}
|
||||
newSubscribers = append(newSubscribers, sb)
|
||||
}
|
||||
m.subscribers[topic] = newSubscribers
|
||||
m.Unlock()
|
||||
}()
|
||||
|
||||
return sub, nil
|
||||
}
|
||||
|
||||
func (m *memoryBroker) Subscribe(ctx context.Context, topic string, handler Handler, opts ...SubscribeOption) (Subscriber, error) {
|
||||
m.RLock()
|
||||
if !m.connected {
|
||||
m.RUnlock()
|
||||
return nil, ErrNotConnected
|
||||
}
|
||||
m.RUnlock()
|
||||
|
||||
sid, err := id.New()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
options := NewSubscribeOptions(opts...)
|
||||
|
||||
sub := &memorySubscriber{
|
||||
exit: make(chan bool, 1),
|
||||
id: sid,
|
||||
topic: topic,
|
||||
handler: handler,
|
||||
opts: options,
|
||||
ctx: ctx,
|
||||
}
|
||||
|
||||
m.Lock()
|
||||
m.subscribers[topic] = append(m.subscribers[topic], sub)
|
||||
m.Unlock()
|
||||
|
||||
go func() {
|
||||
<-sub.exit
|
||||
m.Lock()
|
||||
newSubscribers := make([]*memorySubscriber, 0, len(m.subscribers)-1)
|
||||
for _, sb := range m.subscribers[topic] {
|
||||
if sb.id == sub.id {
|
||||
continue
|
||||
}
|
||||
newSubscribers = append(newSubscribers, sb)
|
||||
}
|
||||
m.subscribers[topic] = newSubscribers
|
||||
m.Unlock()
|
||||
}()
|
||||
|
||||
return sub, nil
|
||||
}
|
||||
|
||||
func (m *memoryBroker) String() string {
|
||||
return "memory"
|
||||
}
|
||||
|
||||
func (m *memoryBroker) Name() string {
|
||||
return m.opts.Name
|
||||
}
|
||||
|
||||
func (m *memoryEvent) Topic() string {
|
||||
return m.topic
|
||||
}
|
||||
|
||||
func (m *memoryEvent) Message() *Message {
|
||||
switch v := m.message.(type) {
|
||||
case *Message:
|
||||
return v
|
||||
case []byte:
|
||||
msg := &Message{}
|
||||
if err := m.opts.Codec.Unmarshal(v, msg); err != nil {
|
||||
if m.opts.Logger.V(logger.ErrorLevel) {
|
||||
m.opts.Logger.Error(m.opts.Context, "[memory]: failed to unmarshal: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return msg
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memoryEvent) Ack() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memoryEvent) Error() error {
|
||||
return m.err
|
||||
}
|
||||
|
||||
func (m *memoryEvent) SetError(err error) {
|
||||
m.err = err
|
||||
}
|
||||
|
||||
func (m *memorySubscriber) Options() SubscribeOptions {
|
||||
return m.opts
|
||||
}
|
||||
|
||||
func (m *memorySubscriber) Topic() string {
|
||||
return m.topic
|
||||
}
|
||||
|
||||
func (m *memorySubscriber) Unsubscribe(ctx context.Context) error {
|
||||
m.exit <- true
|
||||
return nil
|
||||
}
|
||||
|
||||
// NewBroker return new memory broker
|
||||
func NewBroker(opts ...Option) Broker {
|
||||
return &memoryBroker{
|
||||
opts: NewOptions(opts...),
|
||||
subscribers: make(map[string][]*memorySubscriber),
|
||||
}
|
||||
}
|
105
broker/memory_test.go
Normal file
105
broker/memory_test.go
Normal file
@@ -0,0 +1,105 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"go.unistack.org/micro/v3/metadata"
|
||||
)
|
||||
|
||||
func TestMemoryBatchBroker(t *testing.T) {
|
||||
b := NewBroker()
|
||||
ctx := context.Background()
|
||||
|
||||
if err := b.Connect(ctx); err != nil {
|
||||
t.Fatalf("Unexpected connect error %v", err)
|
||||
}
|
||||
|
||||
topic := "test"
|
||||
count := 10
|
||||
|
||||
fn := func(evts Events) error {
|
||||
return evts.Ack()
|
||||
}
|
||||
|
||||
sub, err := b.BatchSubscribe(ctx, topic, fn)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error subscribing %v", err)
|
||||
}
|
||||
|
||||
msgs := make([]*Message, 0, count)
|
||||
for i := 0; i < count; i++ {
|
||||
message := &Message{
|
||||
Header: map[string]string{
|
||||
metadata.HeaderTopic: topic,
|
||||
"foo": "bar",
|
||||
"id": fmt.Sprintf("%d", i),
|
||||
},
|
||||
Body: []byte(`"hello world"`),
|
||||
}
|
||||
msgs = append(msgs, message)
|
||||
}
|
||||
|
||||
if err := b.BatchPublish(ctx, msgs); err != nil {
|
||||
t.Fatalf("Unexpected error publishing %v", err)
|
||||
}
|
||||
|
||||
if err := sub.Unsubscribe(ctx); err != nil {
|
||||
t.Fatalf("Unexpected error unsubscribing from %s: %v", topic, err)
|
||||
}
|
||||
|
||||
if err := b.Disconnect(ctx); err != nil {
|
||||
t.Fatalf("Unexpected connect error %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemoryBroker(t *testing.T) {
|
||||
b := NewBroker()
|
||||
ctx := context.Background()
|
||||
|
||||
if err := b.Connect(ctx); err != nil {
|
||||
t.Fatalf("Unexpected connect error %v", err)
|
||||
}
|
||||
|
||||
topic := "test"
|
||||
count := 10
|
||||
|
||||
fn := func(p Event) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
sub, err := b.Subscribe(ctx, topic, fn)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error subscribing %v", err)
|
||||
}
|
||||
|
||||
msgs := make([]*Message, 0, count)
|
||||
for i := 0; i < count; i++ {
|
||||
message := &Message{
|
||||
Header: map[string]string{
|
||||
metadata.HeaderTopic: topic,
|
||||
"foo": "bar",
|
||||
"id": fmt.Sprintf("%d", i),
|
||||
},
|
||||
Body: []byte(`"hello world"`),
|
||||
}
|
||||
msgs = append(msgs, message)
|
||||
|
||||
if err := b.Publish(ctx, topic, message); err != nil {
|
||||
t.Fatalf("Unexpected error publishing %d err: %v", i, err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := b.BatchPublish(ctx, msgs); err != nil {
|
||||
t.Fatalf("Unexpected error publishing %v", err)
|
||||
}
|
||||
|
||||
if err := sub.Unsubscribe(ctx); err != nil {
|
||||
t.Fatalf("Unexpected error unsubscribing from %s: %v", topic, err)
|
||||
}
|
||||
|
||||
if err := b.Disconnect(ctx); err != nil {
|
||||
t.Fatalf("Unexpected connect error %v", err)
|
||||
}
|
||||
}
|
@@ -1,81 +0,0 @@
|
||||
package broker
|
||||
|
||||
import "context"
|
||||
|
||||
type noopBroker struct {
|
||||
opts Options
|
||||
}
|
||||
|
||||
type noopSubscriber struct {
|
||||
topic string
|
||||
opts SubscribeOptions
|
||||
}
|
||||
|
||||
// NewBroker returns new noop broker
|
||||
func NewBroker(opts ...Option) Broker {
|
||||
return &noopBroker{opts: NewOptions(opts...)}
|
||||
}
|
||||
|
||||
func (n *noopBroker) Name() string {
|
||||
return n.opts.Name
|
||||
}
|
||||
|
||||
// Init initialize broker
|
||||
func (n *noopBroker) Init(opts ...Option) error {
|
||||
for _, o := range opts {
|
||||
o(&n.opts)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Options returns broker Options
|
||||
func (n *noopBroker) Options() Options {
|
||||
return n.opts
|
||||
}
|
||||
|
||||
// Address returns broker address
|
||||
func (n *noopBroker) Address() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Connect connects to broker
|
||||
func (n *noopBroker) Connect(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Disconnect disconnects from broker
|
||||
func (n *noopBroker) Disconnect(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Publish publishes message to broker
|
||||
func (n *noopBroker) Publish(ctx context.Context, topic string, m *Message, opts ...PublishOption) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Subscribe subscribes to broker topic
|
||||
func (n *noopBroker) Subscribe(ctx context.Context, topic string, h Handler, opts ...SubscribeOption) (Subscriber, error) {
|
||||
options := NewSubscribeOptions(opts...)
|
||||
return &noopSubscriber{topic: topic, opts: options}, nil
|
||||
}
|
||||
|
||||
// String return broker string representation
|
||||
func (n *noopBroker) String() string {
|
||||
return "noop"
|
||||
}
|
||||
|
||||
// Options returns subscriber options
|
||||
func (n *noopSubscriber) Options() SubscribeOptions {
|
||||
return n.opts
|
||||
}
|
||||
|
||||
// TOpic returns subscriber topic
|
||||
func (n *noopSubscriber) Topic() string {
|
||||
return n.topic
|
||||
}
|
||||
|
||||
// Unsubscribe unsbscribes from broker topic
|
||||
func (n *noopSubscriber) Unsubscribe(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
@@ -3,35 +3,39 @@ package broker
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"time"
|
||||
|
||||
"github.com/unistack-org/micro/v3/codec"
|
||||
"github.com/unistack-org/micro/v3/logger"
|
||||
"github.com/unistack-org/micro/v3/meter"
|
||||
"github.com/unistack-org/micro/v3/register"
|
||||
"github.com/unistack-org/micro/v3/tracer"
|
||||
"go.unistack.org/micro/v3/codec"
|
||||
"go.unistack.org/micro/v3/logger"
|
||||
"go.unistack.org/micro/v3/meter"
|
||||
"go.unistack.org/micro/v3/register"
|
||||
"go.unistack.org/micro/v3/tracer"
|
||||
)
|
||||
|
||||
// Options struct
|
||||
type Options struct {
|
||||
Name string
|
||||
// Addrs useed by broker
|
||||
Addrs []string
|
||||
// ErrorHandler executed when errors occur processing messages
|
||||
ErrorHandler Handler
|
||||
// Codec used to marshal/unmarshal messages
|
||||
Codec codec.Codec
|
||||
// Logger the used logger
|
||||
Logger logger.Logger
|
||||
// Meter the used for metrics
|
||||
Meter meter.Meter
|
||||
// Tracer used for trace
|
||||
// Tracer used for tracing
|
||||
Tracer tracer.Tracer
|
||||
// TLSConfig for secure communication
|
||||
TLSConfig *tls.Config
|
||||
// Register used for clustering
|
||||
// Register can be used for clustering
|
||||
Register register.Register
|
||||
// Context is used for non default options
|
||||
// Codec holds the codec for marshal/unmarshal
|
||||
Codec codec.Codec
|
||||
// Logger used for logging
|
||||
Logger logger.Logger
|
||||
// Meter used for metrics
|
||||
Meter meter.Meter
|
||||
// Context holds external options
|
||||
Context context.Context
|
||||
// TLSConfig holds tls.TLSConfig options
|
||||
TLSConfig *tls.Config
|
||||
// ErrorHandler used when broker can't unmarshal incoming message
|
||||
ErrorHandler Handler
|
||||
// BatchErrorHandler used when broker can't unmashal incoming messages
|
||||
BatchErrorHandler BatchHandler
|
||||
// Name holds the broker name
|
||||
Name string
|
||||
// Addrs holds the broker address
|
||||
Addrs []string
|
||||
}
|
||||
|
||||
// NewOptions create new Options
|
||||
@@ -59,10 +63,10 @@ func Context(ctx context.Context) Option {
|
||||
|
||||
// PublishOptions struct
|
||||
type PublishOptions struct {
|
||||
// BodyOnly says that only body of the message must be published
|
||||
BodyOnly bool
|
||||
// Context for non default options
|
||||
// Context holds external options
|
||||
Context context.Context
|
||||
// BodyOnly flag says the message contains raw body bytes
|
||||
BodyOnly bool
|
||||
}
|
||||
|
||||
// NewPublishOptions creates PublishOptions struct
|
||||
@@ -70,32 +74,30 @@ func NewPublishOptions(opts ...PublishOption) PublishOptions {
|
||||
options := PublishOptions{
|
||||
Context: context.Background(),
|
||||
}
|
||||
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
// SubscribeOptions struct
|
||||
type SubscribeOptions struct {
|
||||
// AutoAck ack messages if handler returns nil err
|
||||
AutoAck bool
|
||||
|
||||
// ErrorHandler executed when errors occur processing messages
|
||||
ErrorHandler Handler
|
||||
|
||||
// Group for subscriber, Subscribers with the same group name
|
||||
// will create a shared subscription where each
|
||||
// receives a subset of messages.
|
||||
Group string
|
||||
|
||||
// BodyOnly says that consumed only body of the message
|
||||
BodyOnly bool
|
||||
|
||||
// Context is used for non default options
|
||||
// Context holds external options
|
||||
Context context.Context
|
||||
// ErrorHandler used when broker can't unmarshal incoming message
|
||||
ErrorHandler Handler
|
||||
// BatchErrorHandler used when broker can't unmashal incoming messages
|
||||
BatchErrorHandler BatchHandler
|
||||
// Group holds consumer group
|
||||
Group string
|
||||
// AutoAck flag specifies auto ack of incoming message when no error happens
|
||||
AutoAck bool
|
||||
// BodyOnly flag specifies that message contains only body bytes without header
|
||||
BodyOnly bool
|
||||
// BatchSize flag specifies max batch size
|
||||
BatchSize int
|
||||
// BatchWait flag specifies max wait time for batch filling
|
||||
BatchWait time.Duration
|
||||
}
|
||||
|
||||
// Option func
|
||||
@@ -118,23 +120,6 @@ func PublishContext(ctx context.Context) PublishOption {
|
||||
}
|
||||
}
|
||||
|
||||
// SubscribeOption func
|
||||
type SubscribeOption func(*SubscribeOptions)
|
||||
|
||||
// NewSubscribeOptions creates new SubscribeOptions
|
||||
func NewSubscribeOptions(opts ...SubscribeOption) SubscribeOptions {
|
||||
options := SubscribeOptions{
|
||||
AutoAck: true,
|
||||
Context: context.Background(),
|
||||
}
|
||||
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
// Addrs sets the host addresses to be used by the broker
|
||||
func Addrs(addrs ...string) Option {
|
||||
return func(o *Options) {
|
||||
@@ -150,28 +135,6 @@ func Codec(c codec.Codec) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// DisableAutoAck disables auto ack
|
||||
func DisableAutoAck() SubscribeOption {
|
||||
return func(o *SubscribeOptions) {
|
||||
o.AutoAck = false
|
||||
}
|
||||
}
|
||||
|
||||
// SubscribeAutoAck will disable auto acking of messages
|
||||
// after they have been handled.
|
||||
func SubscribeAutoAck(b bool) SubscribeOption {
|
||||
return func(o *SubscribeOptions) {
|
||||
o.AutoAck = b
|
||||
}
|
||||
}
|
||||
|
||||
// SubscribeBodyOnly consumes only body of the message
|
||||
func SubscribeBodyOnly(b bool) SubscribeOption {
|
||||
return func(o *SubscribeOptions) {
|
||||
o.BodyOnly = b
|
||||
}
|
||||
}
|
||||
|
||||
// ErrorHandler will catch all broker errors that cant be handled
|
||||
// in normal way, for example Codec errors
|
||||
func ErrorHandler(h Handler) Option {
|
||||
@@ -180,6 +143,14 @@ func ErrorHandler(h Handler) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// BatchErrorHandler will catch all broker errors that cant be handled
|
||||
// in normal way, for example Codec errors
|
||||
func BatchErrorHandler(h BatchHandler) Option {
|
||||
return func(o *Options) {
|
||||
o.BatchErrorHandler = h
|
||||
}
|
||||
}
|
||||
|
||||
// SubscribeErrorHandler will catch all broker errors that cant be handled
|
||||
// in normal way, for example Codec errors
|
||||
func SubscribeErrorHandler(h Handler) SubscribeOption {
|
||||
@@ -188,6 +159,14 @@ func SubscribeErrorHandler(h Handler) SubscribeOption {
|
||||
}
|
||||
}
|
||||
|
||||
// SubscribeBatchErrorHandler will catch all broker errors that cant be handled
|
||||
// in normal way, for example Codec errors
|
||||
func SubscribeBatchErrorHandler(h BatchHandler) SubscribeOption {
|
||||
return func(o *SubscribeOptions) {
|
||||
o.BatchErrorHandler = h
|
||||
}
|
||||
}
|
||||
|
||||
// Queue sets the subscribers queue
|
||||
// Deprecated
|
||||
func Queue(name string) SubscribeOption {
|
||||
@@ -251,3 +230,55 @@ func SubscribeContext(ctx context.Context) SubscribeOption {
|
||||
o.Context = ctx
|
||||
}
|
||||
}
|
||||
|
||||
// DisableAutoAck disables auto ack
|
||||
// Deprecated
|
||||
func DisableAutoAck() SubscribeOption {
|
||||
return func(o *SubscribeOptions) {
|
||||
o.AutoAck = false
|
||||
}
|
||||
}
|
||||
|
||||
// SubscribeAutoAck contol auto acking of messages
|
||||
// after they have been handled.
|
||||
func SubscribeAutoAck(b bool) SubscribeOption {
|
||||
return func(o *SubscribeOptions) {
|
||||
o.AutoAck = b
|
||||
}
|
||||
}
|
||||
|
||||
// SubscribeBodyOnly consumes only body of the message
|
||||
func SubscribeBodyOnly(b bool) SubscribeOption {
|
||||
return func(o *SubscribeOptions) {
|
||||
o.BodyOnly = b
|
||||
}
|
||||
}
|
||||
|
||||
// SubscribeBatchSize specifies max batch size
|
||||
func SubscribeBatchSize(n int) SubscribeOption {
|
||||
return func(o *SubscribeOptions) {
|
||||
o.BatchSize = n
|
||||
}
|
||||
}
|
||||
|
||||
// SubscribeBatchWait specifies max batch wait time
|
||||
func SubscribeBatchWait(td time.Duration) SubscribeOption {
|
||||
return func(o *SubscribeOptions) {
|
||||
o.BatchWait = td
|
||||
}
|
||||
}
|
||||
|
||||
// SubscribeOption func
|
||||
type SubscribeOption func(*SubscribeOptions)
|
||||
|
||||
// NewSubscribeOptions creates new SubscribeOptions
|
||||
func NewSubscribeOptions(opts ...SubscribeOption) SubscribeOptions {
|
||||
options := SubscribeOptions{
|
||||
AutoAck: true,
|
||||
Context: context.Background(),
|
||||
}
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
@@ -1,5 +1,5 @@
|
||||
// Package build is for building source into a package
|
||||
package build
|
||||
package build // import "go.unistack.org/micro/v3/build"
|
||||
|
||||
// Build is an interface for building packages
|
||||
type Build interface {
|
||||
@@ -21,12 +21,12 @@ type Source struct {
|
||||
|
||||
// Package is packaged format for source
|
||||
type Package struct {
|
||||
// Source of the package
|
||||
Source *Source
|
||||
// Name of the package
|
||||
Name string
|
||||
// Location of the package
|
||||
Path string
|
||||
// Type of package e.g tarball, binary, docker
|
||||
Type string
|
||||
// Source of the package
|
||||
Source *Source
|
||||
}
|
||||
|
@@ -4,7 +4,7 @@ import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/unistack-org/micro/v3/util/backoff"
|
||||
"go.unistack.org/micro/v3/util/backoff"
|
||||
)
|
||||
|
||||
// BackoffFunc is the backoff call func
|
||||
|
@@ -1,17 +1,31 @@
|
||||
// Package client is an interface for an RPC client
|
||||
package client
|
||||
package client // import "go.unistack.org/micro/v3/client"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/unistack-org/micro/v3/codec"
|
||||
"github.com/unistack-org/micro/v3/metadata"
|
||||
"go.unistack.org/micro/v3/codec"
|
||||
"go.unistack.org/micro/v3/metadata"
|
||||
)
|
||||
|
||||
var (
|
||||
// DefaultClient is the global default client
|
||||
DefaultClient Client = NewClient()
|
||||
// DefaultContentType is the default content-type if not specified
|
||||
DefaultContentType = "application/json"
|
||||
// DefaultBackoff is the default backoff function for retries
|
||||
DefaultBackoff = exponentialBackoff
|
||||
// DefaultRetry is the default check-for-retry function for retries
|
||||
DefaultRetry = RetryNever
|
||||
// DefaultRetries is the default number of times a request is tried
|
||||
DefaultRetries = 0
|
||||
// DefaultRequestTimeout is the default request timeout
|
||||
DefaultRequestTimeout = time.Second * 5
|
||||
// DefaultPoolSize sets the connection pool size
|
||||
DefaultPoolSize = 100
|
||||
// DefaultPoolTTL sets the connection pool ttl
|
||||
DefaultPoolTTL = time.Minute
|
||||
)
|
||||
|
||||
// Client is the interface used to make requests to services.
|
||||
@@ -19,13 +33,14 @@ var (
|
||||
// It also supports bidirectional streaming of requests.
|
||||
type Client interface {
|
||||
Name() string
|
||||
Init(...Option) error
|
||||
Init(opts ...Option) error
|
||||
Options() Options
|
||||
NewMessage(topic string, msg interface{}, opts ...MessageOption) Message
|
||||
NewRequest(service, endpoint string, req interface{}, reqOpts ...RequestOption) Request
|
||||
NewRequest(service string, endpoint string, req interface{}, opts ...RequestOption) Request
|
||||
Call(ctx context.Context, req Request, rsp interface{}, opts ...CallOption) error
|
||||
Stream(ctx context.Context, req Request, opts ...CallOption) (Stream, error)
|
||||
Publish(ctx context.Context, msg Message, opts ...PublishOption) error
|
||||
BatchPublish(ctx context.Context, msg []Message, opts ...PublishOption) error
|
||||
String() string
|
||||
}
|
||||
|
||||
@@ -34,6 +49,7 @@ type Message interface {
|
||||
Topic() string
|
||||
Payload() interface{}
|
||||
ContentType() string
|
||||
Metadata() metadata.Metadata
|
||||
}
|
||||
|
||||
// Request is the interface for a synchronous request used by Call or Stream
|
||||
@@ -73,13 +89,19 @@ type Stream interface {
|
||||
// The response read
|
||||
Response() Response
|
||||
// Send will encode and send a request
|
||||
Send(interface{}) error
|
||||
Send(msg interface{}) error
|
||||
// Recv will decode and read a response
|
||||
Recv(interface{}) error
|
||||
Recv(msg interface{}) error
|
||||
// SendMsg will encode and send a request
|
||||
SendMsg(msg interface{}) error
|
||||
// RecvMsg will decode and read a response
|
||||
RecvMsg(msg interface{}) error
|
||||
// Error returns the stream error
|
||||
Error() error
|
||||
// Close closes the stream
|
||||
Close() error
|
||||
// CloseSend closes the send direction of the stream
|
||||
CloseSend() error
|
||||
}
|
||||
|
||||
// Option used by the Client
|
||||
@@ -96,18 +118,3 @@ type MessageOption func(*MessageOptions)
|
||||
|
||||
// RequestOption used by NewRequest
|
||||
type RequestOption func(*RequestOptions)
|
||||
|
||||
var (
|
||||
// DefaultBackoff is the default backoff function for retries
|
||||
DefaultBackoff = exponentialBackoff
|
||||
// DefaultRetry is the default check-for-retry function for retries
|
||||
DefaultRetry = RetryNever
|
||||
// DefaultRetries is the default number of times a request is tried
|
||||
DefaultRetries = 0
|
||||
// DefaultRequestTimeout is the default request timeout
|
||||
DefaultRequestTimeout = time.Second * 5
|
||||
// DefaultPoolSize sets the connection pool size
|
||||
DefaultPoolSize = 100
|
||||
// DefaultPoolTTL sets the connection pool ttl
|
||||
DefaultPoolTTL = time.Minute
|
||||
)
|
||||
|
@@ -4,15 +4,15 @@ import (
|
||||
"context"
|
||||
"sort"
|
||||
|
||||
"github.com/unistack-org/micro/v3/errors"
|
||||
"github.com/unistack-org/micro/v3/router"
|
||||
"go.unistack.org/micro/v3/errors"
|
||||
"go.unistack.org/micro/v3/router"
|
||||
)
|
||||
|
||||
// LookupFunc is used to lookup routes for a service
|
||||
type LookupFunc func(context.Context, Request, CallOptions) ([]string, error)
|
||||
|
||||
// LookupRoute for a request using the router and then choose one using the selector
|
||||
func LookupRoute(ctx context.Context, req Request, opts CallOptions) ([]string, error) {
|
||||
func LookupRoute(_ context.Context, req Request, opts CallOptions) ([]string, error) {
|
||||
// check to see if an address was provided as a call option
|
||||
if len(opts.Address) > 0 {
|
||||
return opts.Address, nil
|
||||
|
140
client/noop.go
140
client/noop.go
@@ -3,26 +3,16 @@ package client
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/unistack-org/micro/v3/broker"
|
||||
"github.com/unistack-org/micro/v3/codec"
|
||||
"github.com/unistack-org/micro/v3/errors"
|
||||
"github.com/unistack-org/micro/v3/metadata"
|
||||
"go.unistack.org/micro/v3/broker"
|
||||
"go.unistack.org/micro/v3/codec"
|
||||
"go.unistack.org/micro/v3/errors"
|
||||
"go.unistack.org/micro/v3/metadata"
|
||||
)
|
||||
|
||||
var (
|
||||
// DefaultCodecs will be used to encode/decode data
|
||||
DefaultCodecs = map[string]codec.Codec{
|
||||
//"application/json": cjson.NewCodec,
|
||||
//"application/json-rpc": cjsonrpc.NewCodec,
|
||||
//"application/protobuf": cproto.NewCodec,
|
||||
//"application/proto-rpc": cprotorpc.NewCodec,
|
||||
"application/octet-stream": codec.NewCodec(),
|
||||
}
|
||||
)
|
||||
|
||||
const (
|
||||
defaultContentType = "application/json"
|
||||
)
|
||||
// DefaultCodecs will be used to encode/decode data
|
||||
var DefaultCodecs = map[string]codec.Codec{
|
||||
"application/octet-stream": codec.NewCodec(),
|
||||
}
|
||||
|
||||
type noopClient struct {
|
||||
opts Options
|
||||
@@ -35,18 +25,27 @@ type noopMessage struct {
|
||||
}
|
||||
|
||||
type noopRequest struct {
|
||||
body interface{}
|
||||
codec codec.Codec
|
||||
service string
|
||||
method string
|
||||
endpoint string
|
||||
contentType string
|
||||
body interface{}
|
||||
codec codec.Codec
|
||||
stream bool
|
||||
}
|
||||
|
||||
// NewClient returns new noop client
|
||||
func NewClient(opts ...Option) Client {
|
||||
return &noopClient{opts: NewOptions(opts...)}
|
||||
nc := &noopClient{opts: NewOptions(opts...)}
|
||||
// wrap in reverse
|
||||
|
||||
c := Client(nc)
|
||||
|
||||
for i := len(nc.opts.Wrappers); i > 0; i-- {
|
||||
c = nc.opts.Wrappers[i-1](c)
|
||||
}
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
func (n *noopClient) Name() string {
|
||||
@@ -120,6 +119,14 @@ func (n *noopStream) Recv(interface{}) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *noopStream) SendMsg(interface{}) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *noopStream) RecvMsg(interface{}) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *noopStream) Error() error {
|
||||
return nil
|
||||
}
|
||||
@@ -128,6 +135,10 @@ func (n *noopStream) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *noopStream) CloseSend() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *noopMessage) Topic() string {
|
||||
return n.topic
|
||||
}
|
||||
@@ -140,6 +151,10 @@ func (n *noopMessage) ContentType() string {
|
||||
return n.opts.ContentType
|
||||
}
|
||||
|
||||
func (n *noopMessage) Metadata() metadata.Metadata {
|
||||
return n.opts.Metadata
|
||||
}
|
||||
|
||||
func (n *noopClient) newCodec(contentType string) (codec.Codec, error) {
|
||||
if cf, ok := n.opts.Codecs[contentType]; ok {
|
||||
return cf, nil
|
||||
@@ -170,11 +185,11 @@ func (n *noopClient) Call(ctx context.Context, req Request, rsp interface{}, opt
|
||||
}
|
||||
|
||||
func (n *noopClient) NewRequest(service, endpoint string, req interface{}, opts ...RequestOption) Request {
|
||||
return &noopRequest{}
|
||||
return &noopRequest{service: service, endpoint: endpoint}
|
||||
}
|
||||
|
||||
func (n *noopClient) NewMessage(topic string, msg interface{}, opts ...MessageOption) Message {
|
||||
options := NewMessageOptions(opts...)
|
||||
options := NewMessageOptions(append([]MessageOption{MessageContentType(n.opts.ContentType)}, opts...)...)
|
||||
return &noopMessage{topic: topic, payload: msg, opts: options}
|
||||
}
|
||||
|
||||
@@ -182,45 +197,60 @@ func (n *noopClient) Stream(ctx context.Context, req Request, opts ...CallOption
|
||||
return &noopStream{}, nil
|
||||
}
|
||||
|
||||
func (n *noopClient) Publish(ctx context.Context, p Message, opts ...PublishOption) error {
|
||||
var body []byte
|
||||
func (n *noopClient) BatchPublish(ctx context.Context, ps []Message, opts ...PublishOption) error {
|
||||
return n.publish(ctx, ps, opts...)
|
||||
}
|
||||
|
||||
func (n *noopClient) Publish(ctx context.Context, p Message, opts ...PublishOption) error {
|
||||
return n.publish(ctx, []Message{p}, opts...)
|
||||
}
|
||||
|
||||
func (n *noopClient) publish(ctx context.Context, ps []Message, opts ...PublishOption) error {
|
||||
options := NewPublishOptions(opts...)
|
||||
|
||||
md, ok := metadata.FromContext(ctx)
|
||||
if !ok {
|
||||
md = metadata.New(0)
|
||||
}
|
||||
md["Content-Type"] = p.ContentType()
|
||||
md["Micro-Topic"] = p.Topic()
|
||||
msgs := make([]*broker.Message, 0, len(ps))
|
||||
|
||||
// passed in raw data
|
||||
if d, ok := p.Payload().(*codec.Frame); ok {
|
||||
body = d.Data
|
||||
} else {
|
||||
// use codec for payload
|
||||
cf, err := n.newCodec(p.ContentType())
|
||||
if err != nil {
|
||||
return errors.InternalServerError("go.micro.client", err.Error())
|
||||
for _, p := range ps {
|
||||
md, ok := metadata.FromOutgoingContext(ctx)
|
||||
if !ok {
|
||||
md = metadata.New(0)
|
||||
}
|
||||
md[metadata.HeaderContentType] = p.ContentType()
|
||||
|
||||
topic := p.Topic()
|
||||
|
||||
// get the exchange
|
||||
if len(options.Exchange) > 0 {
|
||||
topic = options.Exchange
|
||||
}
|
||||
|
||||
// set the body
|
||||
b, err := cf.Marshal(p.Payload())
|
||||
if err != nil {
|
||||
return errors.InternalServerError("go.micro.client", err.Error())
|
||||
md[metadata.HeaderTopic] = topic
|
||||
|
||||
var body []byte
|
||||
|
||||
// passed in raw data
|
||||
if d, ok := p.Payload().(*codec.Frame); ok {
|
||||
body = d.Data
|
||||
} else {
|
||||
// use codec for payload
|
||||
cf, err := n.newCodec(p.ContentType())
|
||||
if err != nil {
|
||||
return errors.InternalServerError("go.micro.client", err.Error())
|
||||
}
|
||||
|
||||
// set the body
|
||||
b, err := cf.Marshal(p.Payload())
|
||||
if err != nil {
|
||||
return errors.InternalServerError("go.micro.client", err.Error())
|
||||
}
|
||||
body = b
|
||||
}
|
||||
body = b
|
||||
|
||||
msgs = append(msgs, &broker.Message{Header: md, Body: body})
|
||||
}
|
||||
|
||||
topic := p.Topic()
|
||||
|
||||
// get the exchange
|
||||
if len(options.Exchange) > 0 {
|
||||
topic = options.Exchange
|
||||
}
|
||||
|
||||
return n.opts.Broker.Publish(ctx, topic, &broker.Message{
|
||||
Header: md,
|
||||
Body: body,
|
||||
}, broker.PublishContext(options.Context))
|
||||
return n.opts.Broker.BatchPublish(ctx, msgs,
|
||||
broker.PublishContext(options.Context),
|
||||
broker.PublishBodyOnly(options.BodyOnly),
|
||||
)
|
||||
}
|
||||
|
@@ -2,51 +2,60 @@ package client
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"time"
|
||||
|
||||
"github.com/unistack-org/micro/v3/broker"
|
||||
"github.com/unistack-org/micro/v3/codec"
|
||||
"github.com/unistack-org/micro/v3/logger"
|
||||
"github.com/unistack-org/micro/v3/meter"
|
||||
"github.com/unistack-org/micro/v3/network/transport"
|
||||
"github.com/unistack-org/micro/v3/register"
|
||||
"github.com/unistack-org/micro/v3/router"
|
||||
"github.com/unistack-org/micro/v3/selector"
|
||||
"github.com/unistack-org/micro/v3/selector/random"
|
||||
"github.com/unistack-org/micro/v3/tracer"
|
||||
"go.unistack.org/micro/v3/broker"
|
||||
"go.unistack.org/micro/v3/codec"
|
||||
"go.unistack.org/micro/v3/logger"
|
||||
"go.unistack.org/micro/v3/metadata"
|
||||
"go.unistack.org/micro/v3/meter"
|
||||
"go.unistack.org/micro/v3/network/transport"
|
||||
"go.unistack.org/micro/v3/register"
|
||||
"go.unistack.org/micro/v3/router"
|
||||
"go.unistack.org/micro/v3/selector"
|
||||
"go.unistack.org/micro/v3/selector/random"
|
||||
"go.unistack.org/micro/v3/tracer"
|
||||
)
|
||||
|
||||
// Options holds client options
|
||||
type Options struct {
|
||||
Name string
|
||||
// Used to select codec
|
||||
ContentType string
|
||||
// Proxy address to send requests via
|
||||
Proxy string
|
||||
|
||||
// Plugged interfaces
|
||||
Broker broker.Broker
|
||||
Codecs map[string]codec.Codec
|
||||
Router router.Router
|
||||
Selector selector.Selector
|
||||
// Transport used for transfer messages
|
||||
Transport transport.Transport
|
||||
Logger logger.Logger
|
||||
Meter meter.Meter
|
||||
// Lookup used for looking up routes
|
||||
Lookup LookupFunc
|
||||
|
||||
// Connection Pool
|
||||
PoolSize int
|
||||
PoolTTL time.Duration
|
||||
Tracer tracer.Tracer
|
||||
// Wrapper that used client
|
||||
Wrappers []Wrapper
|
||||
|
||||
// CallOptions that used by default
|
||||
CallOptions CallOptions
|
||||
|
||||
// Context is used for non default options
|
||||
// Selector used to select needed address
|
||||
Selector selector.Selector
|
||||
// Logger used to log messages
|
||||
Logger logger.Logger
|
||||
// Tracer used for tracing
|
||||
Tracer tracer.Tracer
|
||||
// Broker used to publish messages
|
||||
Broker broker.Broker
|
||||
// Meter used for metrics
|
||||
Meter meter.Meter
|
||||
// Context is used for external options
|
||||
Context context.Context
|
||||
// Router used to get route
|
||||
Router router.Router
|
||||
// TLSConfig specifies tls.Config for secure connection
|
||||
TLSConfig *tls.Config
|
||||
// Codecs map
|
||||
Codecs map[string]codec.Codec
|
||||
// Lookup func used to get destination addr
|
||||
Lookup LookupFunc
|
||||
// Proxy is used for proxy requests
|
||||
Proxy string
|
||||
// ContentType is used to select codec
|
||||
ContentType string
|
||||
// Name is the client name
|
||||
Name string
|
||||
// Wrappers contains wrappers
|
||||
Wrappers []Wrapper
|
||||
// CallOptions contains default CallOptions
|
||||
CallOptions CallOptions
|
||||
// PoolSize connection pool size
|
||||
PoolSize int
|
||||
// PoolTTL connection pool ttl
|
||||
PoolTTL time.Duration
|
||||
}
|
||||
|
||||
// NewCallOptions creates new call options struct
|
||||
@@ -60,34 +69,36 @@ func NewCallOptions(opts ...CallOption) CallOptions {
|
||||
|
||||
// CallOptions holds client call options
|
||||
type CallOptions struct {
|
||||
// Address of remote hosts
|
||||
Address []string
|
||||
// Backoff func
|
||||
Backoff BackoffFunc
|
||||
// Transport Dial Timeout
|
||||
DialTimeout time.Duration
|
||||
// Number of Call attempts
|
||||
Retries int
|
||||
// Check if retriable func
|
||||
Retry RetryFunc
|
||||
// Request/Response timeout
|
||||
RequestTimeout time.Duration
|
||||
// Router to use for this call
|
||||
Router router.Router
|
||||
// Selector to use for the call
|
||||
// Selector selects addr
|
||||
Selector selector.Selector
|
||||
// SelectOptions to use when selecting a route
|
||||
SelectOptions []selector.SelectOption
|
||||
// Stream timeout for the stream
|
||||
StreamTimeout time.Duration
|
||||
// Use the auth token as the authorization header
|
||||
AuthToken bool
|
||||
// Network to lookup the route within
|
||||
Network string
|
||||
// Middleware for low level call func
|
||||
CallWrappers []CallWrapper
|
||||
// Context is uded for non default options
|
||||
// Context used for deadline
|
||||
Context context.Context
|
||||
// Router used for route
|
||||
Router router.Router
|
||||
// Retry func used for retries
|
||||
Retry RetryFunc
|
||||
// Backoff func used for backoff when retry
|
||||
Backoff BackoffFunc
|
||||
// Network name
|
||||
Network string
|
||||
// Content-Type
|
||||
ContentType string
|
||||
// AuthToken string
|
||||
AuthToken string
|
||||
// Address specifies static addr list
|
||||
Address []string
|
||||
// SelectOptions selector options
|
||||
SelectOptions []selector.SelectOption
|
||||
// CallWrappers call wrappers
|
||||
CallWrappers []CallWrapper
|
||||
// StreamTimeout stream timeout
|
||||
StreamTimeout time.Duration
|
||||
// RequestTimeout request timeout
|
||||
RequestTimeout time.Duration
|
||||
// DialTimeout dial timeout
|
||||
DialTimeout time.Duration
|
||||
// Retries specifies retries num
|
||||
Retries int
|
||||
}
|
||||
|
||||
// Context pass context to client
|
||||
@@ -108,16 +119,17 @@ func NewPublishOptions(opts ...PublishOption) PublishOptions {
|
||||
|
||||
// PublishOptions holds publish options
|
||||
type PublishOptions struct {
|
||||
// Exchange is the routing exchange for the message
|
||||
Exchange string
|
||||
// Other options for implementations of the interface
|
||||
// can be stored in a context
|
||||
// Context used for external options
|
||||
Context context.Context
|
||||
// Exchange topic exchange name
|
||||
Exchange string
|
||||
// BodyOnly will publish only message body
|
||||
BodyOnly bool
|
||||
}
|
||||
|
||||
// NewMessageOptions creates message options struct
|
||||
func NewMessageOptions(opts ...MessageOption) MessageOptions {
|
||||
options := MessageOptions{}
|
||||
options := MessageOptions{Metadata: metadata.New(1)}
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
@@ -126,6 +138,10 @@ func NewMessageOptions(opts ...MessageOption) MessageOptions {
|
||||
|
||||
// MessageOptions holds client message options
|
||||
type MessageOptions struct {
|
||||
// Metadata additional metadata
|
||||
Metadata metadata.Metadata
|
||||
// ContentType specify content-type of message
|
||||
// deprecated
|
||||
ContentType string
|
||||
}
|
||||
|
||||
@@ -140,34 +156,38 @@ func NewRequestOptions(opts ...RequestOption) RequestOptions {
|
||||
|
||||
// RequestOptions holds client request options
|
||||
type RequestOptions struct {
|
||||
ContentType string
|
||||
Stream bool
|
||||
// Other options for implementations of the interface
|
||||
// can be stored in a context
|
||||
// Context used for external options
|
||||
Context context.Context
|
||||
// ContentType specify content-type of message
|
||||
ContentType string
|
||||
// Stream flag
|
||||
Stream bool
|
||||
}
|
||||
|
||||
// NewOptions creates new options struct
|
||||
func NewOptions(opts ...Option) Options {
|
||||
options := Options{
|
||||
Context: context.Background(),
|
||||
ContentType: "application/json",
|
||||
ContentType: DefaultContentType,
|
||||
Codecs: make(map[string]codec.Codec),
|
||||
CallOptions: CallOptions{
|
||||
Context: context.Background(),
|
||||
Backoff: DefaultBackoff,
|
||||
Retry: DefaultRetry,
|
||||
Retries: DefaultRetries,
|
||||
RequestTimeout: DefaultRequestTimeout,
|
||||
DialTimeout: transport.DefaultDialTimeout,
|
||||
},
|
||||
Lookup: LookupRoute,
|
||||
PoolSize: DefaultPoolSize,
|
||||
PoolTTL: DefaultPoolTTL,
|
||||
Selector: random.NewSelector(),
|
||||
Logger: logger.DefaultLogger,
|
||||
Broker: broker.DefaultBroker,
|
||||
Meter: meter.DefaultMeter,
|
||||
Tracer: tracer.DefaultTracer,
|
||||
Lookup: LookupRoute,
|
||||
PoolSize: DefaultPoolSize,
|
||||
PoolTTL: DefaultPoolTTL,
|
||||
Selector: random.NewSelector(),
|
||||
Logger: logger.DefaultLogger,
|
||||
Broker: broker.DefaultBroker,
|
||||
Meter: meter.DefaultMeter,
|
||||
Tracer: tracer.DefaultTracer,
|
||||
Router: router.DefaultRouter,
|
||||
Transport: transport.DefaultTransport,
|
||||
}
|
||||
|
||||
for _, o := range opts {
|
||||
@@ -212,7 +232,7 @@ func Codec(contentType string, c codec.Codec) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// Default content type of the client
|
||||
// ContentType used by default if not specified
|
||||
func ContentType(ct string) Option {
|
||||
return func(o *Options) {
|
||||
o.ContentType = ct
|
||||
@@ -251,7 +271,7 @@ func Transport(t transport.Transport) Option {
|
||||
func Register(r register.Register) Option {
|
||||
return func(o *Options) {
|
||||
if o.Router != nil {
|
||||
o.Router.Init(router.Register(r))
|
||||
_ = o.Router.Init(router.Register(r))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -270,22 +290,21 @@ func Selector(s selector.Selector) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// Adds a Wrapper to a list of options passed into the client
|
||||
// Wrap adds a wrapper to the list of options passed into the client
|
||||
func Wrap(w Wrapper) Option {
|
||||
return func(o *Options) {
|
||||
o.Wrappers = append(o.Wrappers, w)
|
||||
}
|
||||
}
|
||||
|
||||
// Adds a Wrapper to the list of CallFunc wrappers
|
||||
// WrapCall adds a wrapper to the list of CallFunc wrappers
|
||||
func WrapCall(cw ...CallWrapper) Option {
|
||||
return func(o *Options) {
|
||||
o.CallOptions.CallWrappers = append(o.CallOptions.CallWrappers, cw...)
|
||||
}
|
||||
}
|
||||
|
||||
// Backoff is used to set the backoff function used
|
||||
// when retrying Calls
|
||||
// Backoff is used to set the backoff function used when retrying Calls
|
||||
func Backoff(fn BackoffFunc) Option {
|
||||
return func(o *Options) {
|
||||
o.CallOptions.Backoff = fn
|
||||
@@ -306,8 +325,23 @@ func Lookup(l LookupFunc) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// TLSConfig specifies a *tls.Config
|
||||
func TLSConfig(t *tls.Config) Option {
|
||||
return func(o *Options) {
|
||||
// set the internal tls
|
||||
o.TLSConfig = t
|
||||
|
||||
// set the default transport if one is not
|
||||
// already set. Required for Init call below.
|
||||
|
||||
// set the transport tls
|
||||
_ = o.Transport.Init(
|
||||
transport.TLSConfig(t),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Retries sets the retry count when making the request.
|
||||
// Should this be a Call Option?
|
||||
func Retries(i int) Option {
|
||||
return func(o *Options) {
|
||||
o.CallOptions.Retries = i
|
||||
@@ -322,7 +356,6 @@ func Retry(fn RetryFunc) Option {
|
||||
}
|
||||
|
||||
// RequestTimeout is the request timeout.
|
||||
// Should this be a Call Option?
|
||||
func RequestTimeout(d time.Duration) Option {
|
||||
return func(o *Options) {
|
||||
o.CallOptions.RequestTimeout = d
|
||||
@@ -336,22 +369,43 @@ func StreamTimeout(d time.Duration) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// Transport dial timeout
|
||||
// DialTimeout sets the dial timeout
|
||||
func DialTimeout(d time.Duration) Option {
|
||||
return func(o *Options) {
|
||||
o.CallOptions.DialTimeout = d
|
||||
}
|
||||
}
|
||||
|
||||
// Call Options
|
||||
|
||||
// WithExchange sets the exchange to route a message through
|
||||
// Deprecated
|
||||
func WithExchange(e string) PublishOption {
|
||||
return func(o *PublishOptions) {
|
||||
o.Exchange = e
|
||||
}
|
||||
}
|
||||
|
||||
// PublishExchange sets the exchange to route a message through
|
||||
func PublishExchange(e string) PublishOption {
|
||||
return func(o *PublishOptions) {
|
||||
o.Exchange = e
|
||||
}
|
||||
}
|
||||
|
||||
// WithBodyOnly publish only message body
|
||||
// DERECATED
|
||||
func WithBodyOnly(b bool) PublishOption {
|
||||
return func(o *PublishOptions) {
|
||||
o.BodyOnly = b
|
||||
}
|
||||
}
|
||||
|
||||
// PublishBodyOnly publish only message body
|
||||
func PublishBodyOnly(b bool) PublishOption {
|
||||
return func(o *PublishOptions) {
|
||||
o.BodyOnly = b
|
||||
}
|
||||
}
|
||||
|
||||
// PublishContext sets the context in publish options
|
||||
func PublishContext(ctx context.Context) PublishOption {
|
||||
return func(o *PublishOptions) {
|
||||
@@ -359,6 +413,13 @@ func PublishContext(ctx context.Context) PublishOption {
|
||||
}
|
||||
}
|
||||
|
||||
// WithContentType specifies call content type
|
||||
func WithContentType(ct string) CallOption {
|
||||
return func(o *CallOptions) {
|
||||
o.ContentType = ct
|
||||
}
|
||||
}
|
||||
|
||||
// WithAddress sets the remote addresses to use rather than using service discovery
|
||||
func WithAddress(a ...string) CallOption {
|
||||
return func(o *CallOptions) {
|
||||
@@ -422,9 +483,9 @@ func WithDialTimeout(d time.Duration) CallOption {
|
||||
|
||||
// WithAuthToken is a CallOption which overrides the
|
||||
// authorization header with the services own auth token
|
||||
func WithAuthToken() CallOption {
|
||||
func WithAuthToken(t string) CallOption {
|
||||
return func(o *CallOptions) {
|
||||
o.AuthToken = true
|
||||
o.AuthToken = t
|
||||
}
|
||||
}
|
||||
|
||||
@@ -457,24 +518,39 @@ func WithSelectOptions(sops ...selector.SelectOption) CallOption {
|
||||
}
|
||||
|
||||
// WithMessageContentType sets the message content type
|
||||
// Deprecated
|
||||
func WithMessageContentType(ct string) MessageOption {
|
||||
return func(o *MessageOptions) {
|
||||
o.Metadata.Set(metadata.HeaderContentType, ct)
|
||||
o.ContentType = ct
|
||||
}
|
||||
}
|
||||
|
||||
// Request Options
|
||||
|
||||
// WithContentType specifies request content type
|
||||
func WithContentType(ct string) RequestOption {
|
||||
return func(o *RequestOptions) {
|
||||
// MessageContentType sets the message content type
|
||||
func MessageContentType(ct string) MessageOption {
|
||||
return func(o *MessageOptions) {
|
||||
o.Metadata.Set(metadata.HeaderContentType, ct)
|
||||
o.ContentType = ct
|
||||
}
|
||||
}
|
||||
|
||||
// MessageMetadata sets the message metadata
|
||||
func MessageMetadata(k, v string) MessageOption {
|
||||
return func(o *MessageOptions) {
|
||||
o.Metadata.Set(k, v)
|
||||
}
|
||||
}
|
||||
|
||||
// StreamingRequest specifies that request is streaming
|
||||
func StreamingRequest() RequestOption {
|
||||
func StreamingRequest(b bool) RequestOption {
|
||||
return func(o *RequestOptions) {
|
||||
o.Stream = true
|
||||
o.Stream = b
|
||||
}
|
||||
}
|
||||
|
||||
// RequestContentType specifies request content type
|
||||
func RequestContentType(ct string) RequestOption {
|
||||
return func(o *RequestOptions) {
|
||||
o.ContentType = ct
|
||||
}
|
||||
}
|
||||
|
@@ -3,7 +3,7 @@ package client
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/unistack-org/micro/v3/errors"
|
||||
"go.unistack.org/micro/v3/errors"
|
||||
)
|
||||
|
||||
// RetryFunc that returning either false or a non-nil error will result in the call not being retried
|
||||
@@ -20,7 +20,7 @@ func RetryNever(ctx context.Context, req Request, retryCount int, err error) (bo
|
||||
}
|
||||
|
||||
// RetryOnError retries a request on a 500 or timeout error
|
||||
func RetryOnError(ctx context.Context, req Request, retryCount int, err error) (bool, error) {
|
||||
func RetryOnError(_ context.Context, _ Request, _ int, err error) (bool, error) {
|
||||
if err == nil {
|
||||
return false, nil
|
||||
}
|
||||
|
@@ -1,16 +1,16 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"github.com/unistack-org/micro/v3/codec"
|
||||
"go.unistack.org/micro/v3/codec"
|
||||
)
|
||||
|
||||
type testRequest struct {
|
||||
codec codec.Codec
|
||||
body interface{}
|
||||
service string
|
||||
method string
|
||||
endpoint string
|
||||
contentType string
|
||||
codec codec.Codec
|
||||
body interface{}
|
||||
opts RequestOptions
|
||||
}
|
||||
|
||||
|
@@ -1,15 +1,15 @@
|
||||
// Package codec is an interface for encoding messages
|
||||
package codec
|
||||
package codec // import "go.unistack.org/micro/v3/codec"
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
|
||||
"github.com/unistack-org/micro/v3/metadata"
|
||||
"go.unistack.org/micro/v3/metadata"
|
||||
)
|
||||
|
||||
// Message types
|
||||
const (
|
||||
// Message types
|
||||
Error MessageType = iota
|
||||
Request
|
||||
Response
|
||||
@@ -25,11 +25,14 @@ var (
|
||||
|
||||
var (
|
||||
// DefaultMaxMsgSize specifies how much data codec can handle
|
||||
DefaultMaxMsgSize int = 1024 * 1024 * 4 // 4Mb
|
||||
DefaultCodec Codec = NewCodec()
|
||||
DefaultMaxMsgSize = 1024 * 1024 * 4 // 4Mb
|
||||
// DefaultCodec is the global default codec
|
||||
DefaultCodec Codec = NewCodec()
|
||||
// DefaultTagName specifies struct tag name to control codec Marshal/Unmarshal
|
||||
DefaultTagName = "codec"
|
||||
)
|
||||
|
||||
// MessageType
|
||||
// MessageType specifies message type for codec
|
||||
type MessageType int
|
||||
|
||||
// Codec encodes/decodes various types of messages used within micro.
|
||||
@@ -38,11 +41,11 @@ type MessageType int
|
||||
// connection. ReadBody may be called with a nil argument to force the
|
||||
// body to be read and discarded.
|
||||
type Codec interface {
|
||||
ReadHeader(io.Reader, *Message, MessageType) error
|
||||
ReadBody(io.Reader, interface{}) error
|
||||
Write(io.Writer, *Message, interface{}) error
|
||||
Marshal(interface{}) ([]byte, error)
|
||||
Unmarshal([]byte, interface{}) error
|
||||
ReadHeader(r io.Reader, m *Message, mt MessageType) error
|
||||
ReadBody(r io.Reader, v interface{}) error
|
||||
Write(w io.Writer, m *Message, v interface{}) error
|
||||
Marshal(v interface{}, opts ...Option) ([]byte, error)
|
||||
Unmarshal(b []byte, v interface{}, opts ...Option) error
|
||||
String() string
|
||||
}
|
||||
|
||||
@@ -50,19 +53,34 @@ type Codec interface {
|
||||
// the communication, likely followed by the body.
|
||||
// In the case of an error, body may be nil.
|
||||
type Message struct {
|
||||
Id string
|
||||
Type MessageType
|
||||
Header metadata.Metadata
|
||||
Target string
|
||||
Method string
|
||||
Endpoint string
|
||||
Error string
|
||||
|
||||
// The values read from the socket
|
||||
Header metadata.Metadata
|
||||
Body []byte
|
||||
ID string
|
||||
Body []byte
|
||||
Type MessageType
|
||||
}
|
||||
|
||||
// NewMessage creates new codec message
|
||||
func NewMessage(t MessageType) *Message {
|
||||
return &Message{Type: t, Header: metadata.New(0)}
|
||||
}
|
||||
|
||||
// MarshalAppend calls codec.Marshal(v) and returns the data appended to buf.
|
||||
// If codec implements MarshalAppend, that is called instead.
|
||||
func MarshalAppend(buf []byte, c Codec, v interface{}, opts ...Option) ([]byte, error) {
|
||||
if nc, ok := c.(interface {
|
||||
MarshalAppend([]byte, interface{}, ...Option) ([]byte, error)
|
||||
}); ok {
|
||||
return nc.MarshalAppend(buf, v, opts...)
|
||||
}
|
||||
|
||||
mbuf, err := c.Marshal(v, opts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return append(buf, mbuf...), nil
|
||||
}
|
||||
|
34
codec/context.go
Normal file
34
codec/context.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package codec
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
type codecKey struct{}
|
||||
|
||||
// FromContext returns codec from context
|
||||
func FromContext(ctx context.Context) (Codec, bool) {
|
||||
if ctx == nil {
|
||||
return nil, false
|
||||
}
|
||||
c, ok := ctx.Value(codecKey{}).(Codec)
|
||||
return c, ok
|
||||
}
|
||||
|
||||
// NewContext put codec in context
|
||||
func NewContext(ctx context.Context, c Codec) context.Context {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
return context.WithValue(ctx, codecKey{}, c)
|
||||
}
|
||||
|
||||
// SetOption returns a function to setup a context with given value
|
||||
func SetOption(k, v interface{}) Option {
|
||||
return func(o *Options) {
|
||||
if o.Context == nil {
|
||||
o.Context = context.Background()
|
||||
}
|
||||
o.Context = context.WithValue(o.Context, k, v)
|
||||
}
|
||||
}
|
45
codec/frame.go
Normal file
45
codec/frame.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package codec
|
||||
|
||||
// Frame gives us the ability to define raw data to send over the pipes
|
||||
type Frame struct {
|
||||
Data []byte
|
||||
}
|
||||
|
||||
// NewFrame returns new frame with data
|
||||
func NewFrame(data []byte) *Frame {
|
||||
return &Frame{Data: data}
|
||||
}
|
||||
|
||||
// MarshalJSON returns frame data
|
||||
func (m *Frame) MarshalJSON() ([]byte, error) {
|
||||
return m.Marshal()
|
||||
}
|
||||
|
||||
// UnmarshalJSON set frame data
|
||||
func (m *Frame) UnmarshalJSON(data []byte) error {
|
||||
return m.Unmarshal(data)
|
||||
}
|
||||
|
||||
// ProtoMessage noop func
|
||||
func (m *Frame) ProtoMessage() {}
|
||||
|
||||
// Reset resets frame
|
||||
func (m *Frame) Reset() {
|
||||
*m = Frame{}
|
||||
}
|
||||
|
||||
// String returns frame as string
|
||||
func (m *Frame) String() string {
|
||||
return string(m.Data)
|
||||
}
|
||||
|
||||
// Marshal returns frame data
|
||||
func (m *Frame) Marshal() ([]byte, error) {
|
||||
return m.Data, nil
|
||||
}
|
||||
|
||||
// Unmarshal set frame data
|
||||
func (m *Frame) Unmarshal(data []byte) error {
|
||||
m.Data = data
|
||||
return nil
|
||||
}
|
28
codec/frame.proto
Normal file
28
codec/frame.proto
Normal file
@@ -0,0 +1,28 @@
|
||||
// Copyright 2021 Unistack LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
syntax = "proto3";
|
||||
|
||||
package micro.codec;
|
||||
|
||||
option cc_enable_arenas = true;
|
||||
option go_package = "go.unistack.org/micro/v3/codec;codec";
|
||||
option java_multiple_files = true;
|
||||
option java_outer_classname = "MicroCodec";
|
||||
option java_package = "micro.codec";
|
||||
option objc_class_prefix = "MCODEC";
|
||||
|
||||
message Frame {
|
||||
bytes data = 1;
|
||||
}
|
@@ -1,16 +1,12 @@
|
||||
package codec
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
)
|
||||
|
||||
type noopCodec struct {
|
||||
}
|
||||
|
||||
// Frame gives us the ability to define raw data to send over the pipes
|
||||
type Frame struct {
|
||||
Data []byte
|
||||
opts Options
|
||||
}
|
||||
|
||||
func (c *noopCodec) ReadHeader(conn io.Reader, m *Message, t MessageType) error {
|
||||
@@ -19,7 +15,7 @@ func (c *noopCodec) ReadHeader(conn io.Reader, m *Message, t MessageType) error
|
||||
|
||||
func (c *noopCodec) ReadBody(conn io.Reader, b interface{}) error {
|
||||
// read bytes
|
||||
buf, err := ioutil.ReadAll(conn)
|
||||
buf, err := io.ReadAll(conn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -29,18 +25,14 @@ func (c *noopCodec) ReadBody(conn io.Reader, b interface{}) error {
|
||||
}
|
||||
|
||||
switch v := b.(type) {
|
||||
case string:
|
||||
v = string(buf)
|
||||
case *string:
|
||||
*v = string(buf)
|
||||
case []byte:
|
||||
v = buf
|
||||
case *[]byte:
|
||||
*v = buf
|
||||
case *Frame:
|
||||
v.Data = buf
|
||||
default:
|
||||
return ErrInvalidMessage
|
||||
return json.Unmarshal(buf, v)
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -64,7 +56,11 @@ func (c *noopCodec) Write(conn io.Writer, m *Message, b interface{}) error {
|
||||
case []byte:
|
||||
v = vb
|
||||
default:
|
||||
return ErrInvalidMessage
|
||||
var err error
|
||||
v, err = json.Marshal(vb)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
_, err := conn.Write(v)
|
||||
return err
|
||||
@@ -75,11 +71,11 @@ func (c *noopCodec) String() string {
|
||||
}
|
||||
|
||||
// NewCodec returns new noop codec
|
||||
func NewCodec() Codec {
|
||||
return &noopCodec{}
|
||||
func NewCodec(opts ...Option) Codec {
|
||||
return &noopCodec{opts: NewOptions(opts...)}
|
||||
}
|
||||
|
||||
func (c *noopCodec) Marshal(v interface{}) ([]byte, error) {
|
||||
func (c *noopCodec) Marshal(v interface{}, opts ...Option) ([]byte, error) {
|
||||
if v == nil {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -98,30 +94,28 @@ func (c *noopCodec) Marshal(v interface{}) ([]byte, error) {
|
||||
case *Message:
|
||||
return ve.Body, nil
|
||||
}
|
||||
return nil, ErrInvalidMessage
|
||||
|
||||
return json.Marshal(v)
|
||||
}
|
||||
|
||||
func (c *noopCodec) Unmarshal(d []byte, v interface{}) error {
|
||||
var err error
|
||||
func (c *noopCodec) Unmarshal(d []byte, v interface{}, opts ...Option) error {
|
||||
if v == nil {
|
||||
return nil
|
||||
}
|
||||
switch ve := v.(type) {
|
||||
case string:
|
||||
ve = string(d)
|
||||
case *string:
|
||||
*ve = string(d)
|
||||
case []byte:
|
||||
ve = d
|
||||
return nil
|
||||
case *[]byte:
|
||||
*ve = d
|
||||
return nil
|
||||
case *Frame:
|
||||
ve.Data = d
|
||||
return nil
|
||||
case *Message:
|
||||
ve.Body = d
|
||||
default:
|
||||
err = ErrInvalidMessage
|
||||
return nil
|
||||
}
|
||||
|
||||
return err
|
||||
return json.Unmarshal(d, v)
|
||||
}
|
||||
|
34
codec/noop_test.go
Normal file
34
codec/noop_test.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package codec
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNoopBytes(t *testing.T) {
|
||||
req := []byte("test req")
|
||||
rsp := make([]byte, len(req))
|
||||
|
||||
nc := NewCodec()
|
||||
if err := nc.Unmarshal(req, &rsp); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(req, rsp) {
|
||||
t.Fatalf("req not eq rsp: %s != %s", req, rsp)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoopString(t *testing.T) {
|
||||
req := []byte("test req")
|
||||
var rsp string
|
||||
|
||||
nc := NewCodec()
|
||||
if err := nc.Unmarshal(req, &rsp); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(req, []byte(rsp)) {
|
||||
t.Fatalf("req not eq rsp: %s != %s", req, rsp)
|
||||
}
|
||||
}
|
@@ -1,9 +1,11 @@
|
||||
package codec
|
||||
|
||||
import (
|
||||
"github.com/unistack-org/micro/v3/logger"
|
||||
"github.com/unistack-org/micro/v3/meter"
|
||||
"github.com/unistack-org/micro/v3/tracer"
|
||||
"context"
|
||||
|
||||
"go.unistack.org/micro/v3/logger"
|
||||
"go.unistack.org/micro/v3/meter"
|
||||
"go.unistack.org/micro/v3/tracer"
|
||||
)
|
||||
|
||||
// Option func
|
||||
@@ -11,10 +13,18 @@ type Option func(*Options)
|
||||
|
||||
// Options contains codec options
|
||||
type Options struct {
|
||||
// Meter used for metrics
|
||||
Meter meter.Meter
|
||||
// Logger used for logging
|
||||
Logger logger.Logger
|
||||
// Tracer used for tracing
|
||||
Tracer tracer.Tracer
|
||||
// Context stores additional codec options
|
||||
Context context.Context
|
||||
// TagName specifies tag name in struct to control codec
|
||||
TagName string
|
||||
// MaxMsgSize specifies max messages size that reads by codec
|
||||
MaxMsgSize int
|
||||
Meter meter.Meter
|
||||
Logger logger.Logger
|
||||
Tracer tracer.Tracer
|
||||
}
|
||||
|
||||
// MaxMsgSize sets the max message size
|
||||
@@ -24,6 +34,13 @@ func MaxMsgSize(n int) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// TagName sets the codec tag name in struct
|
||||
func TagName(n string) Option {
|
||||
return func(o *Options) {
|
||||
o.TagName = n
|
||||
}
|
||||
}
|
||||
|
||||
// Logger sets the logger
|
||||
func Logger(l logger.Logger) Option {
|
||||
return func(o *Options) {
|
||||
@@ -45,12 +62,15 @@ func Meter(m meter.Meter) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// NewOptions returns new options
|
||||
func NewOptions(opts ...Option) Options {
|
||||
options := Options{
|
||||
Context: context.Background(),
|
||||
Logger: logger.DefaultLogger,
|
||||
Meter: meter.DefaultMeter,
|
||||
Tracer: tracer.DefaultTracer,
|
||||
MaxMsgSize: DefaultMaxMsgSize,
|
||||
TagName: DefaultTagName,
|
||||
}
|
||||
|
||||
for _, o := range opts {
|
||||
|
@@ -1,15 +1,20 @@
|
||||
// Package config is an interface for dynamic configuration.
|
||||
package config
|
||||
package config // import "go.unistack.org/micro/v3/config"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
// DefaultConfig default config
|
||||
DefaultConfig Config = NewConfig()
|
||||
)
|
||||
// DefaultConfig default config
|
||||
var DefaultConfig Config = NewConfig()
|
||||
|
||||
// DefaultWatcherMinInterval default min interval for poll changes
|
||||
var DefaultWatcherMinInterval = 5 * time.Second
|
||||
|
||||
// DefaultWatcherMaxInterval default max interval for poll changes
|
||||
var DefaultWatcherMaxInterval = 9 * time.Second
|
||||
|
||||
var (
|
||||
// ErrCodecMissing is returned when codec needed and not specified
|
||||
@@ -18,39 +23,96 @@ var (
|
||||
ErrInvalidStruct = errors.New("invalid struct specified")
|
||||
// ErrWatcherStopped is returned when source watcher has been stopped
|
||||
ErrWatcherStopped = errors.New("watcher stopped")
|
||||
// ErrWatcherNotImplemented returned when config does not implement watch
|
||||
ErrWatcherNotImplemented = errors.New("watcher not implemented")
|
||||
)
|
||||
|
||||
// Config is an interface abstraction for dynamic configuration
|
||||
type Config interface {
|
||||
// Name returns name of config
|
||||
Name() string
|
||||
// Init the config
|
||||
Init(opts ...Option) error
|
||||
// Options in the config
|
||||
Options() Options
|
||||
// Load config from sources
|
||||
Load(context.Context) error
|
||||
Load(context.Context, ...LoadOption) error
|
||||
// Save config to sources
|
||||
Save(context.Context) error
|
||||
// Watch a value for changes
|
||||
// Watch(interface{}) (Watcher, error)
|
||||
Save(context.Context, ...SaveOption) error
|
||||
// Watch a config for changes
|
||||
Watch(context.Context, ...WatchOption) (Watcher, error)
|
||||
// String returns config type name
|
||||
String() string
|
||||
}
|
||||
|
||||
// Watcher is the config watcher
|
||||
//type Watcher interface {
|
||||
// Next() (, error)
|
||||
// Stop() error
|
||||
//}
|
||||
type Watcher interface {
|
||||
// Next blocks until update happens or error returned
|
||||
Next() (map[string]interface{}, error)
|
||||
// Stop stops watcher
|
||||
Stop() error
|
||||
}
|
||||
|
||||
// Load loads config from config sources
|
||||
func Load(ctx context.Context, cs ...Config) error {
|
||||
func Load(ctx context.Context, cs []Config, opts ...LoadOption) error {
|
||||
var err error
|
||||
for _, c := range cs {
|
||||
if err = c.Init(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = c.Load(ctx); err != nil {
|
||||
if err = c.Load(ctx, opts...); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var (
|
||||
DefaultAfterLoad = func(ctx context.Context, c Config) error {
|
||||
for _, fn := range c.Options().AfterLoad {
|
||||
if err := fn(ctx, c); err != nil {
|
||||
c.Options().Logger.Errorf(ctx, "%s AfterLoad err: %v", c.String(), err)
|
||||
if !c.Options().AllowFail {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
DefaultAfterSave = func(ctx context.Context, c Config) error {
|
||||
for _, fn := range c.Options().AfterSave {
|
||||
if err := fn(ctx, c); err != nil {
|
||||
c.Options().Logger.Errorf(ctx, "%s AfterSave err: %v", c.String(), err)
|
||||
if !c.Options().AllowFail {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
DefaultBeforeLoad = func(ctx context.Context, c Config) error {
|
||||
for _, fn := range c.Options().BeforeLoad {
|
||||
if err := fn(ctx, c); err != nil {
|
||||
c.Options().Logger.Errorf(ctx, "%s BeforeLoad err: %v", c.String(), err)
|
||||
if !c.Options().AllowFail {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
DefaultBeforeSave = func(ctx context.Context, c Config) error {
|
||||
for _, fn := range c.Options().BeforeSave {
|
||||
if err := fn(ctx, c); err != nil {
|
||||
c.Options().Logger.Errorf(ctx, "%s BeforeSavec err: %v", c.String(), err)
|
||||
if !c.Options().AllowFail {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
)
|
||||
|
@@ -6,6 +6,7 @@ import (
|
||||
|
||||
type configKey struct{}
|
||||
|
||||
// FromContext returns store from context
|
||||
func FromContext(ctx context.Context) (Config, bool) {
|
||||
if ctx == nil {
|
||||
return nil, false
|
||||
@@ -14,6 +15,7 @@ func FromContext(ctx context.Context) (Config, bool) {
|
||||
return c, ok
|
||||
}
|
||||
|
||||
// NewContext put store in context
|
||||
func NewContext(ctx context.Context, c Config) context.Context {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
@@ -30,3 +32,33 @@ func SetOption(k, v interface{}) Option {
|
||||
o.Context = context.WithValue(o.Context, k, v)
|
||||
}
|
||||
}
|
||||
|
||||
// SetSaveOption returns a function to setup a context with given value
|
||||
func SetSaveOption(k, v interface{}) SaveOption {
|
||||
return func(o *SaveOptions) {
|
||||
if o.Context == nil {
|
||||
o.Context = context.Background()
|
||||
}
|
||||
o.Context = context.WithValue(o.Context, k, v)
|
||||
}
|
||||
}
|
||||
|
||||
// SetLoadOption returns a function to setup a context with given value
|
||||
func SetLoadOption(k, v interface{}) LoadOption {
|
||||
return func(o *LoadOptions) {
|
||||
if o.Context == nil {
|
||||
o.Context = context.Background()
|
||||
}
|
||||
o.Context = context.WithValue(o.Context, k, v)
|
||||
}
|
||||
}
|
||||
|
||||
// SetWatchOption returns a function to setup a context with given value
|
||||
func SetWatchOption(k, v interface{}) WatchOption {
|
||||
return func(o *WatchOptions) {
|
||||
if o.Context == nil {
|
||||
o.Context = context.Background()
|
||||
}
|
||||
o.Context = context.WithValue(o.Context, k, v)
|
||||
}
|
||||
}
|
||||
|
@@ -7,7 +7,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/imdario/mergo"
|
||||
rutil "github.com/unistack-org/micro/v3/util/reflect"
|
||||
rutil "go.unistack.org/micro/v3/util/reflect"
|
||||
)
|
||||
|
||||
type defaultConfig struct {
|
||||
@@ -25,35 +25,53 @@ func (c *defaultConfig) Init(opts ...Option) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *defaultConfig) Load(ctx context.Context) error {
|
||||
for _, fn := range c.opts.BeforeLoad {
|
||||
if err := fn(ctx, c); err != nil && !c.opts.AllowFail {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
src, err := rutil.Zero(c.opts.Struct)
|
||||
if err == nil {
|
||||
valueOf := reflect.ValueOf(src)
|
||||
if err = c.fillValues(ctx, valueOf); err == nil {
|
||||
err = mergo.Merge(c.opts.Struct, src, mergo.WithOverride, mergo.WithTypeCheck, mergo.WithAppendSlice)
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil && !c.opts.AllowFail {
|
||||
func (c *defaultConfig) Load(ctx context.Context, opts ...LoadOption) error {
|
||||
if err := DefaultBeforeLoad(ctx, c); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, fn := range c.opts.AfterLoad {
|
||||
if err := fn(ctx, c); err != nil && !c.opts.AllowFail {
|
||||
options := NewLoadOptions(opts...)
|
||||
mopts := []func(*mergo.Config){mergo.WithTypeCheck}
|
||||
if options.Override {
|
||||
mopts = append(mopts, mergo.WithOverride)
|
||||
}
|
||||
if options.Append {
|
||||
mopts = append(mopts, mergo.WithAppendSlice)
|
||||
}
|
||||
|
||||
dst := c.opts.Struct
|
||||
if options.Struct != nil {
|
||||
dst = options.Struct
|
||||
}
|
||||
|
||||
src, err := rutil.Zero(dst)
|
||||
if err != nil {
|
||||
if !c.opts.AllowFail {
|
||||
return err
|
||||
}
|
||||
return DefaultAfterLoad(ctx, c)
|
||||
}
|
||||
|
||||
if err = fillValues(reflect.ValueOf(src), c.opts.StructTag); err == nil {
|
||||
err = mergo.Merge(dst, src, mopts...)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
c.opts.Logger.Errorf(ctx, "default load error: %v", err)
|
||||
if !c.opts.AllowFail {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := DefaultAfterLoad(ctx, c); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *defaultConfig) fillValue(ctx context.Context, value reflect.Value, val string) error {
|
||||
//nolint:gocyclo
|
||||
func fillValue(value reflect.Value, val string) error {
|
||||
if !rutil.IsEmpty(value) {
|
||||
return nil
|
||||
}
|
||||
@@ -70,10 +88,10 @@ func (c *defaultConfig) fillValue(ctx context.Context, value reflect.Value, val
|
||||
kv := strings.FieldsFunc(nval, func(c rune) bool { return c == '=' })
|
||||
mkey := reflect.Indirect(reflect.New(kt))
|
||||
mval := reflect.Indirect(reflect.New(et))
|
||||
if err := c.fillValue(ctx, mkey, kv[0]); err != nil {
|
||||
if err := fillValue(mkey, kv[0]); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := c.fillValue(ctx, mval, kv[1]); err != nil {
|
||||
if err := fillValue(mval, kv[1]); err != nil {
|
||||
return err
|
||||
}
|
||||
value.SetMapIndex(mkey, mval)
|
||||
@@ -83,7 +101,7 @@ func (c *defaultConfig) fillValue(ctx context.Context, value reflect.Value, val
|
||||
value.Set(reflect.MakeSlice(reflect.SliceOf(value.Type().Elem()), len(nvals), len(nvals)))
|
||||
for idx, nval := range nvals {
|
||||
nvalue := reflect.Indirect(reflect.New(value.Type().Elem()))
|
||||
if err := c.fillValue(ctx, nvalue, nval); err != nil {
|
||||
if err := fillValue(nvalue, nval); err != nil {
|
||||
return err
|
||||
}
|
||||
value.Index(idx).Set(nvalue)
|
||||
@@ -107,7 +125,7 @@ func (c *defaultConfig) fillValue(ctx context.Context, value reflect.Value, val
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value.Set(reflect.ValueOf(float64(v)))
|
||||
value.Set(reflect.ValueOf(v))
|
||||
case reflect.Int:
|
||||
v, err := strconv.ParseInt(val, 10, 0)
|
||||
if err != nil {
|
||||
@@ -137,7 +155,7 @@ func (c *defaultConfig) fillValue(ctx context.Context, value reflect.Value, val
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value.Set(reflect.ValueOf(int64(v)))
|
||||
value.Set(reflect.ValueOf(v))
|
||||
case reflect.Uint:
|
||||
v, err := strconv.ParseUint(val, 10, 0)
|
||||
if err != nil {
|
||||
@@ -167,12 +185,12 @@ func (c *defaultConfig) fillValue(ctx context.Context, value reflect.Value, val
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value.Set(reflect.ValueOf(uint64(v)))
|
||||
value.Set(reflect.ValueOf(v))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *defaultConfig) fillValues(ctx context.Context, valueOf reflect.Value) error {
|
||||
func fillValues(valueOf reflect.Value, tname string) error {
|
||||
var values reflect.Value
|
||||
|
||||
if valueOf.Kind() == reflect.Ptr {
|
||||
@@ -199,7 +217,7 @@ func (c *defaultConfig) fillValues(ctx context.Context, valueOf reflect.Value) e
|
||||
switch value.Kind() {
|
||||
case reflect.Struct:
|
||||
value.Set(reflect.Indirect(reflect.New(value.Type())))
|
||||
if err := c.fillValues(ctx, value); err != nil {
|
||||
if err := fillValues(value, tname); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
@@ -213,17 +231,17 @@ func (c *defaultConfig) fillValues(ctx context.Context, valueOf reflect.Value) e
|
||||
value.Set(reflect.New(value.Type().Elem()))
|
||||
}
|
||||
value = value.Elem()
|
||||
if err := c.fillValues(ctx, value); err != nil {
|
||||
if err := fillValues(value, tname); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
tag, ok := field.Tag.Lookup(c.opts.StructTag)
|
||||
tag, ok := field.Tag.Lookup(tname)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
if err := c.fillValue(ctx, value, tag); err != nil {
|
||||
if err := fillValue(value, tag); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -231,17 +249,13 @@ func (c *defaultConfig) fillValues(ctx context.Context, valueOf reflect.Value) e
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *defaultConfig) Save(ctx context.Context) error {
|
||||
for _, fn := range c.opts.BeforeSave {
|
||||
if err := fn(ctx, c); err != nil && !c.opts.AllowFail {
|
||||
return err
|
||||
}
|
||||
func (c *defaultConfig) Save(ctx context.Context, opts ...SaveOption) error {
|
||||
if err := DefaultBeforeSave(ctx, c); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, fn := range c.opts.AfterSave {
|
||||
if err := fn(ctx, c); err != nil && !c.opts.AllowFail {
|
||||
return err
|
||||
}
|
||||
if err := DefaultAfterSave(ctx, c); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -251,6 +265,15 @@ func (c *defaultConfig) String() string {
|
||||
return "default"
|
||||
}
|
||||
|
||||
func (c *defaultConfig) Name() string {
|
||||
return c.opts.Name
|
||||
}
|
||||
|
||||
func (c *defaultConfig) Watch(ctx context.Context, opts ...WatchOption) (Watcher, error) {
|
||||
return nil, ErrWatcherNotImplemented
|
||||
}
|
||||
|
||||
// NewConfig returns new default config source
|
||||
func NewConfig(opts ...Option) Config {
|
||||
options := NewOptions(opts...)
|
||||
if len(options.StructTag) == 0 {
|
||||
|
@@ -5,35 +5,35 @@ import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/unistack-org/micro/v3/config"
|
||||
"go.unistack.org/micro/v3/config"
|
||||
)
|
||||
|
||||
type Cfg struct {
|
||||
StringValue string `default:"string_value"`
|
||||
IntValue int `default:"99"`
|
||||
IgnoreValue string `json:"-"`
|
||||
StructValue struct {
|
||||
StringValue string `default:"string_value"`
|
||||
}
|
||||
IntValue int `default:"99"`
|
||||
}
|
||||
|
||||
func TestDefault(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
conf := &Cfg{IntValue: 10}
|
||||
blfn := func(ctx context.Context, cfg config.Config) error {
|
||||
conf, ok := cfg.Options().Struct.(*Cfg)
|
||||
nconf, ok := cfg.Options().Struct.(*Cfg)
|
||||
if !ok {
|
||||
return fmt.Errorf("failed to get Struct from options: %v", cfg.Options())
|
||||
}
|
||||
conf.StringValue = "before_load"
|
||||
nconf.StringValue = "before_load"
|
||||
return nil
|
||||
}
|
||||
alfn := func(ctx context.Context, cfg config.Config) error {
|
||||
conf, ok := cfg.Options().Struct.(*Cfg)
|
||||
nconf, ok := cfg.Options().Struct.(*Cfg)
|
||||
if !ok {
|
||||
return fmt.Errorf("failed to get Struct from options: %v", cfg.Options())
|
||||
}
|
||||
conf.StringValue = "after_load"
|
||||
nconf.StringValue = "after_load"
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -47,6 +47,6 @@ func TestDefault(t *testing.T) {
|
||||
if conf.StringValue != "after_load" {
|
||||
t.Fatal("AfterLoad option not working")
|
||||
}
|
||||
|
||||
t.Logf("%#+v\n", conf)
|
||||
_ = conf
|
||||
// t.Logf("%#+v\n", conf)
|
||||
}
|
||||
|
@@ -2,38 +2,48 @@ package config
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/unistack-org/micro/v3/codec"
|
||||
"github.com/unistack-org/micro/v3/logger"
|
||||
"github.com/unistack-org/micro/v3/meter"
|
||||
"github.com/unistack-org/micro/v3/tracer"
|
||||
"go.unistack.org/micro/v3/codec"
|
||||
"go.unistack.org/micro/v3/logger"
|
||||
"go.unistack.org/micro/v3/meter"
|
||||
"go.unistack.org/micro/v3/tracer"
|
||||
)
|
||||
|
||||
// Options hold the config options
|
||||
type Options struct {
|
||||
Name string
|
||||
AllowFail bool
|
||||
BeforeLoad []func(context.Context, Config) error
|
||||
AfterLoad []func(context.Context, Config) error
|
||||
BeforeSave []func(context.Context, Config) error
|
||||
AfterSave []func(context.Context, Config) error
|
||||
// Struct that holds config data
|
||||
// Struct holds the destination config struct
|
||||
Struct interface{}
|
||||
// StructTag name
|
||||
StructTag string
|
||||
// Logger that will be used
|
||||
Logger logger.Logger
|
||||
// Meter that will be used
|
||||
Meter meter.Meter
|
||||
// Tracer used for trace
|
||||
Tracer tracer.Tracer
|
||||
// Codec that used for load/save
|
||||
Codec codec.Codec
|
||||
// Context for alternative data
|
||||
// Tracer that will be used
|
||||
Tracer tracer.Tracer
|
||||
// Meter that will be used
|
||||
Meter meter.Meter
|
||||
// Logger that will be used
|
||||
Logger logger.Logger
|
||||
// Context used for external options
|
||||
Context context.Context
|
||||
// Name of the config
|
||||
Name string
|
||||
// StructTag name
|
||||
StructTag string
|
||||
// BeforeSave contains slice of funcs that runs before save
|
||||
BeforeSave []func(context.Context, Config) error
|
||||
// AfterLoad contains slice of funcs that runs after load
|
||||
AfterLoad []func(context.Context, Config) error
|
||||
// BeforeLoad contains slice of funcs that runs before load
|
||||
BeforeLoad []func(context.Context, Config) error
|
||||
// AfterSave contains slice of funcs that runs after save
|
||||
AfterSave []func(context.Context, Config) error
|
||||
// AllowFail flag to allow fail in config source
|
||||
AllowFail bool
|
||||
}
|
||||
|
||||
// Option function signature
|
||||
type Option func(o *Options)
|
||||
|
||||
// NewOptions new options struct with filed values
|
||||
func NewOptions(opts ...Option) Options {
|
||||
options := Options{
|
||||
Logger: logger.DefaultLogger,
|
||||
@@ -48,36 +58,107 @@ func NewOptions(opts ...Option) Options {
|
||||
return options
|
||||
}
|
||||
|
||||
// LoadOption function signature
|
||||
type LoadOption func(o *LoadOptions)
|
||||
|
||||
// LoadOptions struct
|
||||
type LoadOptions struct {
|
||||
Struct interface{}
|
||||
Override bool
|
||||
Append bool
|
||||
Context context.Context
|
||||
}
|
||||
|
||||
func NewLoadOptions(opts ...LoadOption) LoadOptions {
|
||||
options := LoadOptions{}
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
||||
// LoadOverride override values when load
|
||||
func LoadOverride(b bool) LoadOption {
|
||||
return func(o *LoadOptions) {
|
||||
o.Override = b
|
||||
}
|
||||
}
|
||||
|
||||
// LoadAppend override values when load
|
||||
func LoadAppend(b bool) LoadOption {
|
||||
return func(o *LoadOptions) {
|
||||
o.Append = b
|
||||
}
|
||||
}
|
||||
|
||||
// LoadStruct override struct for loading
|
||||
func LoadStruct(src interface{}) LoadOption {
|
||||
return func(o *LoadOptions) {
|
||||
o.Struct = src
|
||||
}
|
||||
}
|
||||
|
||||
// SaveOption function signature
|
||||
type SaveOption func(o *SaveOptions)
|
||||
|
||||
// SaveOptions struct
|
||||
type SaveOptions struct {
|
||||
Struct interface{}
|
||||
Context context.Context
|
||||
}
|
||||
|
||||
// SaveStruct override struct for save to config
|
||||
func SaveStruct(src interface{}) SaveOption {
|
||||
return func(o *SaveOptions) {
|
||||
o.Struct = src
|
||||
}
|
||||
}
|
||||
|
||||
// NewSaveOptions fill SaveOptions struct
|
||||
func NewSaveOptions(opts ...SaveOption) SaveOptions {
|
||||
options := SaveOptions{}
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
||||
// AllowFail allows config source to fail
|
||||
func AllowFail(b bool) Option {
|
||||
return func(o *Options) {
|
||||
o.AllowFail = b
|
||||
}
|
||||
}
|
||||
|
||||
// BeforeLoad run funcs before config load
|
||||
func BeforeLoad(fn ...func(context.Context, Config) error) Option {
|
||||
return func(o *Options) {
|
||||
o.BeforeLoad = fn
|
||||
}
|
||||
}
|
||||
|
||||
// AfterLoad run funcs after config load
|
||||
func AfterLoad(fn ...func(context.Context, Config) error) Option {
|
||||
return func(o *Options) {
|
||||
o.AfterLoad = fn
|
||||
}
|
||||
}
|
||||
|
||||
// BeforeSave run funcs before save
|
||||
func BeforeSave(fn ...func(context.Context, Config) error) Option {
|
||||
return func(o *Options) {
|
||||
o.BeforeSave = fn
|
||||
}
|
||||
}
|
||||
|
||||
// AfterSave run fncs after save
|
||||
func AfterSave(fn ...func(context.Context, Config) error) Option {
|
||||
return func(o *Options) {
|
||||
o.AfterSave = fn
|
||||
}
|
||||
}
|
||||
|
||||
// Context pass context
|
||||
func Context(ctx context.Context) Option {
|
||||
return func(o *Options) {
|
||||
o.Context = ctx
|
||||
@@ -91,6 +172,7 @@ func Codec(c codec.Codec) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// Logger sets the logger
|
||||
func Logger(l logger.Logger) Option {
|
||||
return func(o *Options) {
|
||||
o.Logger = l
|
||||
@@ -111,7 +193,7 @@ func Struct(v interface{}) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// StructTag
|
||||
// StructTag sets the struct tag that used for filling
|
||||
func StructTag(name string) Option {
|
||||
return func(o *Options) {
|
||||
o.StructTag = name
|
||||
@@ -124,3 +206,60 @@ func Name(n string) Option {
|
||||
o.Name = n
|
||||
}
|
||||
}
|
||||
|
||||
// WatchOptions struuct
|
||||
type WatchOptions struct {
|
||||
// Context used by non default options
|
||||
Context context.Context
|
||||
// Struct for filling
|
||||
Struct interface{}
|
||||
// MinInterval specifies the min time.Duration interval for poll changes
|
||||
MinInterval time.Duration
|
||||
// MaxInterval specifies the max time.Duration interval for poll changes
|
||||
MaxInterval time.Duration
|
||||
// Coalesce multiple events to one
|
||||
Coalesce bool
|
||||
}
|
||||
|
||||
type WatchOption func(*WatchOptions)
|
||||
|
||||
func NewWatchOptions(opts ...WatchOption) WatchOptions {
|
||||
options := WatchOptions{
|
||||
Context: context.Background(),
|
||||
MinInterval: DefaultWatcherMinInterval,
|
||||
MaxInterval: DefaultWatcherMaxInterval,
|
||||
}
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
||||
// WatchContext pass context
|
||||
func WatchContext(ctx context.Context) WatchOption {
|
||||
return func(o *WatchOptions) {
|
||||
o.Context = ctx
|
||||
}
|
||||
}
|
||||
|
||||
// WatchCoalesce controls watch event combining
|
||||
func WatchCoalesce(b bool) WatchOption {
|
||||
return func(o *WatchOptions) {
|
||||
o.Coalesce = b
|
||||
}
|
||||
}
|
||||
|
||||
// WatchInterval specifies min and max time.Duration for pulling changes
|
||||
func WatchInterval(min, max time.Duration) WatchOption {
|
||||
return func(o *WatchOptions) {
|
||||
o.MinInterval = min
|
||||
o.MaxInterval = max
|
||||
}
|
||||
}
|
||||
|
||||
// WatchStruct overrides struct for fill
|
||||
func WatchStruct(src interface{}) WatchOption {
|
||||
return func(o *WatchOptions) {
|
||||
o.Struct = src
|
||||
}
|
||||
}
|
||||
|
@@ -1,26 +0,0 @@
|
||||
package config_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
rutil "github.com/unistack-org/micro/v3/util/reflect"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Value string
|
||||
SubConfig *SubConfig
|
||||
Config *Config
|
||||
}
|
||||
|
||||
type SubConfig struct {
|
||||
Value string
|
||||
}
|
||||
|
||||
func TestReflect(t *testing.T) {
|
||||
cfg1 := &Config{Value: "cfg1", Config: &Config{Value: "cfg1_1"}, SubConfig: &SubConfig{Value: "cfg1"}}
|
||||
cfg2, err := rutil.Zero(cfg1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Logf("dst: %#+v\n", cfg2)
|
||||
}
|
@@ -1,2 +0,0 @@
|
||||
// Package debug provides interfaces for service debugging
|
||||
package debug
|
@@ -1,190 +0,0 @@
|
||||
// Package kubernetes is a logger implementing (github.com/unistack-org/micro/v3/debug/log).Log
|
||||
package kubernetes
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"sort"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/unistack-org/micro/v3/debug/log"
|
||||
"github.com/unistack-org/micro/v3/metadata"
|
||||
"github.com/unistack-org/micro/v3/util/kubernetes/client"
|
||||
)
|
||||
|
||||
type klog struct {
|
||||
client client.Client
|
||||
|
||||
log.Options
|
||||
}
|
||||
|
||||
func (k *klog) podLogStream(podName string, stream *kubeStream) {
|
||||
p := make(map[string]string)
|
||||
p["follow"] = "true"
|
||||
|
||||
// get the logs for the pod
|
||||
body, err := k.client.Log(&client.Resource{
|
||||
Name: podName,
|
||||
Kind: "pod",
|
||||
}, client.LogParams(p))
|
||||
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "%v", err)
|
||||
return
|
||||
}
|
||||
|
||||
s := bufio.NewScanner(body)
|
||||
defer body.Close()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-stream.stop:
|
||||
return
|
||||
default:
|
||||
if s.Scan() {
|
||||
record := k.parse(s.Text())
|
||||
stream.stream <- record
|
||||
} else {
|
||||
// TODO: is there a blocking call
|
||||
// rather than a sleep loop?
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (k *klog) getMatchingPods() ([]string, error) {
|
||||
r := &client.Resource{
|
||||
Kind: "pod",
|
||||
Value: new(client.PodList),
|
||||
}
|
||||
|
||||
l := make(map[string]string)
|
||||
|
||||
l["name"] = client.Format(k.Options.Name)
|
||||
// TODO: specify micro:service
|
||||
// l["micro"] = "service"
|
||||
|
||||
if err := k.client.Get(r, client.GetLabels(l)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var matches []string
|
||||
|
||||
for _, p := range r.Value.(*client.PodList).Items {
|
||||
// find labels that match the name
|
||||
if p.Metadata.Labels["name"] == client.Format(k.Options.Name) {
|
||||
matches = append(matches, p.Metadata.Name)
|
||||
}
|
||||
}
|
||||
|
||||
return matches, nil
|
||||
}
|
||||
|
||||
func (k *klog) parse(line string) log.Record {
|
||||
record := log.Record{}
|
||||
|
||||
if err := json.Unmarshal([]byte(line), &record); err != nil {
|
||||
record.Timestamp = time.Now().UTC()
|
||||
record.Message = line
|
||||
record.Metadata = metadata.New(1)
|
||||
}
|
||||
|
||||
record.Metadata["service"] = k.Options.Name
|
||||
|
||||
return record
|
||||
}
|
||||
|
||||
func (k *klog) Read(options ...log.ReadOption) ([]log.Record, error) {
|
||||
opts := &log.ReadOptions{}
|
||||
for _, o := range options {
|
||||
o(opts)
|
||||
}
|
||||
pods, err := k.getMatchingPods()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var records []log.Record
|
||||
|
||||
for _, pod := range pods {
|
||||
logParams := make(map[string]string)
|
||||
|
||||
if !opts.Since.Equal(time.Time{}) {
|
||||
logParams["sinceSeconds"] = strconv.Itoa(int(time.Since(opts.Since).Seconds()))
|
||||
}
|
||||
|
||||
if opts.Count != 0 {
|
||||
logParams["tailLines"] = strconv.Itoa(opts.Count)
|
||||
}
|
||||
|
||||
if opts.Stream {
|
||||
logParams["follow"] = "true"
|
||||
}
|
||||
|
||||
logs, err := k.client.Log(&client.Resource{
|
||||
Name: pod,
|
||||
Kind: "pod",
|
||||
}, client.LogParams(logParams))
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer logs.Close()
|
||||
|
||||
s := bufio.NewScanner(logs)
|
||||
|
||||
for s.Scan() {
|
||||
record := k.parse(s.Text())
|
||||
record.Metadata["pod"] = pod
|
||||
records = append(records, record)
|
||||
}
|
||||
}
|
||||
|
||||
// sort the records
|
||||
sort.Slice(records, func(i, j int) bool { return records[i].Timestamp.Before(records[j].Timestamp) })
|
||||
|
||||
return records, nil
|
||||
}
|
||||
|
||||
func (k *klog) Write(l log.Record) error {
|
||||
return write(l)
|
||||
}
|
||||
|
||||
func (k *klog) Stream() (log.Stream, error) {
|
||||
// find the matching pods
|
||||
pods, err := k.getMatchingPods()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
stream := &kubeStream{
|
||||
stream: make(chan log.Record),
|
||||
stop: make(chan bool),
|
||||
}
|
||||
|
||||
// stream from the individual pods
|
||||
for _, pod := range pods {
|
||||
go k.podLogStream(pod, stream)
|
||||
}
|
||||
|
||||
return stream, nil
|
||||
}
|
||||
|
||||
// NewLog returns a configured Kubernetes logger
|
||||
func NewLog(opts ...log.Option) log.Log {
|
||||
klog := &klog{}
|
||||
for _, o := range opts {
|
||||
o(&klog.Options)
|
||||
}
|
||||
|
||||
if len(os.Getenv("KUBERNETES_SERVICE_HOST")) > 0 {
|
||||
klog.client = client.NewClusterClient()
|
||||
} else {
|
||||
klog.client = client.NewLocalClient()
|
||||
}
|
||||
return klog
|
||||
}
|
@@ -1,71 +0,0 @@
|
||||
package kubernetes
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/unistack-org/micro/v3/debug/log"
|
||||
)
|
||||
|
||||
func TestKubernetes(t *testing.T) {
|
||||
if len(os.Getenv("INTEGRATION_TESTS")) > 0 {
|
||||
t.Skip()
|
||||
}
|
||||
|
||||
k := NewLog(log.Name("micro-network"))
|
||||
|
||||
r, w, err := os.Pipe()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
s := os.Stderr
|
||||
os.Stderr = w
|
||||
meta := make(map[string]string)
|
||||
|
||||
write := log.Record{
|
||||
Timestamp: time.Unix(0, 0).UTC(),
|
||||
Message: "Test log entry",
|
||||
Metadata: meta,
|
||||
}
|
||||
|
||||
meta["foo"] = "bar"
|
||||
|
||||
k.Write(write)
|
||||
b := &bytes.Buffer{}
|
||||
w.Close()
|
||||
io.Copy(b, r)
|
||||
os.Stderr = s
|
||||
|
||||
var read log.Record
|
||||
|
||||
if err := json.Unmarshal(b.Bytes(), &read); err != nil {
|
||||
t.Fatalf("json.Unmarshal failed: %s", err.Error())
|
||||
}
|
||||
|
||||
assert.Equal(t, write, read, "Write was not equal")
|
||||
|
||||
records, err := k.Read()
|
||||
assert.Nil(t, err, "Read should not error")
|
||||
assert.NotNil(t, records, "Read should return records")
|
||||
|
||||
stream, err := k.Stream()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
records = nil
|
||||
|
||||
go stream.Stop()
|
||||
|
||||
for s := range stream.Chan() {
|
||||
records = append(records, s)
|
||||
}
|
||||
|
||||
assert.Equal(t, 0, len(records), "Stream should return nothing")
|
||||
}
|
@@ -1,44 +0,0 @@
|
||||
package kubernetes
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"github.com/unistack-org/micro/v3/debug/log"
|
||||
)
|
||||
|
||||
func write(l log.Record) error {
|
||||
m, err := json.Marshal(l)
|
||||
if err == nil {
|
||||
_, err := fmt.Fprintf(os.Stderr, "%s", m)
|
||||
return err
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
type kubeStream struct {
|
||||
// the k8s log stream
|
||||
stream chan log.Record
|
||||
sync.Mutex
|
||||
// the stop chan
|
||||
stop chan bool
|
||||
}
|
||||
|
||||
func (k *kubeStream) Chan() <-chan log.Record {
|
||||
return k.stream
|
||||
}
|
||||
|
||||
func (k *kubeStream) Stop() error {
|
||||
k.Lock()
|
||||
defer k.Unlock()
|
||||
select {
|
||||
case <-k.stop:
|
||||
return nil
|
||||
default:
|
||||
close(k.stop)
|
||||
close(k.stream)
|
||||
}
|
||||
return nil
|
||||
}
|
@@ -1,58 +0,0 @@
|
||||
// Package log provides debug logging
|
||||
package log
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/unistack-org/micro/v3/metadata"
|
||||
)
|
||||
|
||||
var (
|
||||
// Default buffer size if any
|
||||
DefaultSize = 256
|
||||
// Default formatter
|
||||
DefaultFormat = TextFormat
|
||||
)
|
||||
|
||||
// Log is debug log interface for reading and writing logs
|
||||
type Log interface {
|
||||
// Read reads log entries from the logger
|
||||
Read(...ReadOption) ([]Record, error)
|
||||
// Write writes records to log
|
||||
Write(Record) error
|
||||
// Stream log records
|
||||
Stream() (Stream, error)
|
||||
}
|
||||
|
||||
// Record is log record entry
|
||||
type Record struct {
|
||||
// Timestamp of logged event
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
// Metadata to enrich log record
|
||||
Metadata metadata.Metadata `json:"metadata"`
|
||||
// Value contains log entry
|
||||
Message interface{} `json:"message"`
|
||||
}
|
||||
|
||||
// Stream returns a log stream
|
||||
type Stream interface {
|
||||
Chan() <-chan Record
|
||||
Stop() error
|
||||
}
|
||||
|
||||
// Format is a function which formats the output
|
||||
type FormatFunc func(Record) string
|
||||
|
||||
// TextFormat returns text format
|
||||
func TextFormat(r Record) string {
|
||||
t := r.Timestamp.Format("2006-01-02 15:04:05")
|
||||
return fmt.Sprintf("%s %v", t, r.Message)
|
||||
}
|
||||
|
||||
// JSONFormat is a json Format func
|
||||
func JSONFormat(r Record) string {
|
||||
b, _ := json.Marshal(r)
|
||||
return string(b)
|
||||
}
|
@@ -1,115 +0,0 @@
|
||||
// Package memory provides an in memory log buffer
|
||||
package memory
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/unistack-org/micro/v3/debug/log"
|
||||
"github.com/unistack-org/micro/v3/metadata"
|
||||
"github.com/unistack-org/micro/v3/util/ring"
|
||||
)
|
||||
|
||||
// memoryLog is default micro log
|
||||
type memoryLog struct {
|
||||
*ring.Buffer
|
||||
}
|
||||
|
||||
// NewLog returns default Logger with
|
||||
func NewLog(opts ...log.Option) log.Log {
|
||||
// get default options
|
||||
options := log.DefaultOptions()
|
||||
|
||||
// apply requested options
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
return &memoryLog{
|
||||
Buffer: ring.New(options.Size),
|
||||
}
|
||||
}
|
||||
|
||||
// Write writes logs into logger
|
||||
func (l *memoryLog) Write(r log.Record) error {
|
||||
l.Buffer.Put(fmt.Sprint(r.Message))
|
||||
return nil
|
||||
}
|
||||
|
||||
// Read reads logs and returns them
|
||||
func (l *memoryLog) Read(opts ...log.ReadOption) ([]log.Record, error) {
|
||||
options := log.ReadOptions{}
|
||||
// initialize the read options
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
var entries []*ring.Entry
|
||||
// if Since options ha sbeen specified we honor it
|
||||
if !options.Since.IsZero() {
|
||||
entries = l.Buffer.Since(options.Since)
|
||||
}
|
||||
|
||||
// only if we specified valid count constraint
|
||||
// do we end up doing some serious if-else kung-fu
|
||||
// if since constraint has been provided
|
||||
// we return *count* number of logs since the given timestamp;
|
||||
// otherwise we return last count number of logs
|
||||
if options.Count > 0 {
|
||||
switch len(entries) > 0 {
|
||||
case true:
|
||||
// if we request fewer logs than what since constraint gives us
|
||||
if options.Count < len(entries) {
|
||||
entries = entries[0:options.Count]
|
||||
}
|
||||
default:
|
||||
entries = l.Buffer.Get(options.Count)
|
||||
}
|
||||
}
|
||||
|
||||
records := make([]log.Record, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
record := log.Record{
|
||||
Timestamp: entry.Timestamp,
|
||||
Message: entry.Value,
|
||||
}
|
||||
records = append(records, record)
|
||||
}
|
||||
|
||||
return records, nil
|
||||
}
|
||||
|
||||
// Stream returns channel for reading log records
|
||||
// along with a stop channel, close it when done
|
||||
func (l *memoryLog) Stream() (log.Stream, error) {
|
||||
// get stream channel from ring buffer
|
||||
stream, stop := l.Buffer.Stream()
|
||||
// make a buffered channel
|
||||
records := make(chan log.Record, 128)
|
||||
// get last 10 records
|
||||
last10 := l.Buffer.Get(10)
|
||||
|
||||
// stream the log records
|
||||
go func() {
|
||||
// first send last 10 records
|
||||
for _, entry := range last10 {
|
||||
records <- log.Record{
|
||||
Timestamp: entry.Timestamp,
|
||||
Message: entry.Value,
|
||||
Metadata: metadata.New(0),
|
||||
}
|
||||
}
|
||||
// now stream continuously
|
||||
for entry := range stream {
|
||||
records <- log.Record{
|
||||
Timestamp: entry.Timestamp,
|
||||
Message: entry.Value,
|
||||
Metadata: metadata.New(0),
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return &logStream{
|
||||
stream: records,
|
||||
stop: stop,
|
||||
}, nil
|
||||
}
|
@@ -1,32 +0,0 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/unistack-org/micro/v3/debug/log"
|
||||
)
|
||||
|
||||
func TestLogger(t *testing.T) {
|
||||
// set size to some value
|
||||
size := 100
|
||||
// override the global logger
|
||||
lg := NewLog(log.Size(size))
|
||||
// make sure we have the right size of the logger ring buffer
|
||||
if lg.(*memoryLog).Size() != size {
|
||||
t.Errorf("expected buffer size: %d, got: %d", size, lg.(*memoryLog).Size())
|
||||
}
|
||||
|
||||
// Log some cruft
|
||||
lg.Write(log.Record{Message: "foobar"})
|
||||
lg.Write(log.Record{Message: "foo bar"})
|
||||
|
||||
// Check if the logs are stored in the logger ring buffer
|
||||
expected := []string{"foobar", "foo bar"}
|
||||
entries, _ := lg.Read(log.Count(len(expected)))
|
||||
for i, entry := range entries {
|
||||
if !reflect.DeepEqual(entry.Message, expected[i]) {
|
||||
t.Errorf("expected %s, got %s", expected[i], entry.Message)
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,24 +0,0 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"github.com/unistack-org/micro/v3/debug/log"
|
||||
)
|
||||
|
||||
type logStream struct {
|
||||
stream <-chan log.Record
|
||||
stop chan bool
|
||||
}
|
||||
|
||||
func (l *logStream) Chan() <-chan log.Record {
|
||||
return l.stream
|
||||
}
|
||||
|
||||
func (l *logStream) Stop() error {
|
||||
select {
|
||||
case <-l.stop:
|
||||
return nil
|
||||
default:
|
||||
close(l.stop)
|
||||
}
|
||||
return nil
|
||||
}
|
@@ -1,23 +0,0 @@
|
||||
package noop
|
||||
|
||||
import (
|
||||
"github.com/unistack-org/micro/v3/debug/log"
|
||||
)
|
||||
|
||||
type noop struct{}
|
||||
|
||||
func (n *noop) Read(...log.ReadOption) ([]log.Record, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (n *noop) Write(log.Record) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *noop) Stream() (log.Stream, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func NewLog(opts ...log.Option) log.Log {
|
||||
return new(noop)
|
||||
}
|
@@ -1,70 +0,0 @@
|
||||
package log
|
||||
|
||||
import "time"
|
||||
|
||||
// Option used by the logger
|
||||
type Option func(*Options)
|
||||
|
||||
// Options are logger options
|
||||
type Options struct {
|
||||
// Name of the log
|
||||
Name string
|
||||
// Size is the size of ring buffer
|
||||
Size int
|
||||
// Format specifies the output format
|
||||
Format FormatFunc
|
||||
}
|
||||
|
||||
// Name of the log
|
||||
func Name(n string) Option {
|
||||
return func(o *Options) {
|
||||
o.Name = n
|
||||
}
|
||||
}
|
||||
|
||||
// Size sets the size of the ring buffer
|
||||
func Size(s int) Option {
|
||||
return func(o *Options) {
|
||||
o.Size = s
|
||||
}
|
||||
}
|
||||
|
||||
func Format(f FormatFunc) Option {
|
||||
return func(o *Options) {
|
||||
o.Format = f
|
||||
}
|
||||
}
|
||||
|
||||
// DefaultOptions returns default options
|
||||
func DefaultOptions() Options {
|
||||
return Options{
|
||||
Size: DefaultSize,
|
||||
}
|
||||
}
|
||||
|
||||
// ReadOptions for querying the logs
|
||||
type ReadOptions struct {
|
||||
// Since what time in past to return the logs
|
||||
Since time.Time
|
||||
// Count specifies number of logs to return
|
||||
Count int
|
||||
// Stream requests continuous log stream
|
||||
Stream bool
|
||||
}
|
||||
|
||||
// ReadOption used for reading the logs
|
||||
type ReadOption func(*ReadOptions)
|
||||
|
||||
// Since sets the time since which to return the log records
|
||||
func Since(s time.Time) ReadOption {
|
||||
return func(o *ReadOptions) {
|
||||
o.Since = s
|
||||
}
|
||||
}
|
||||
|
||||
// Count sets the number of log records to return
|
||||
func Count(c int) ReadOption {
|
||||
return func(o *ReadOptions) {
|
||||
o.Count = c
|
||||
}
|
||||
}
|
@@ -1,89 +0,0 @@
|
||||
package stats
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/unistack-org/micro/v3/debug/stats"
|
||||
"github.com/unistack-org/micro/v3/util/ring"
|
||||
)
|
||||
|
||||
type memoryStats struct {
|
||||
// used to store past stats
|
||||
buffer *ring.Buffer
|
||||
|
||||
sync.RWMutex
|
||||
started int64
|
||||
requests uint64
|
||||
errors uint64
|
||||
}
|
||||
|
||||
func (s *memoryStats) snapshot() *stats.Stat {
|
||||
s.RLock()
|
||||
defer s.RUnlock()
|
||||
|
||||
var mstat runtime.MemStats
|
||||
runtime.ReadMemStats(&mstat)
|
||||
|
||||
now := time.Now().Unix()
|
||||
|
||||
return &stats.Stat{
|
||||
Timestamp: now,
|
||||
Started: s.started,
|
||||
Uptime: now - s.started,
|
||||
Memory: mstat.Alloc,
|
||||
GC: mstat.PauseTotalNs,
|
||||
Threads: uint64(runtime.NumGoroutine()),
|
||||
Requests: s.requests,
|
||||
Errors: s.errors,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *memoryStats) Read() ([]*stats.Stat, error) {
|
||||
buf := s.buffer.Get(s.buffer.Size())
|
||||
var buffer []*stats.Stat
|
||||
|
||||
// get a value from the buffer if it exists
|
||||
for _, b := range buf {
|
||||
stat, ok := b.Value.(*stats.Stat)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
buffer = append(buffer, stat)
|
||||
}
|
||||
|
||||
// get a snapshot
|
||||
buffer = append(buffer, s.snapshot())
|
||||
|
||||
return buffer, nil
|
||||
}
|
||||
|
||||
func (s *memoryStats) Write(stat *stats.Stat) error {
|
||||
s.buffer.Put(stat)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *memoryStats) Record(err error) error {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
|
||||
// increment the total request count
|
||||
s.requests++
|
||||
|
||||
// increment the error count
|
||||
if err != nil {
|
||||
s.errors++
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// NewStats returns a new in memory stats buffer
|
||||
// TODO add options
|
||||
func NewStats() stats.Stats {
|
||||
return &memoryStats{
|
||||
started: time.Now().Unix(),
|
||||
buffer: ring.New(1),
|
||||
}
|
||||
}
|
@@ -1,32 +0,0 @@
|
||||
// Package stats provides runtime stats
|
||||
package stats
|
||||
|
||||
// Stats provides stats interface
|
||||
type Stats interface {
|
||||
// Read stat snapshot
|
||||
Read() ([]*Stat, error)
|
||||
// Write a stat snapshot
|
||||
Write(*Stat) error
|
||||
// Record a request
|
||||
Record(error) error
|
||||
}
|
||||
|
||||
// A runtime stat
|
||||
type Stat struct {
|
||||
// Timestamp of recording
|
||||
Timestamp int64
|
||||
// Start time as unix timestamp
|
||||
Started int64
|
||||
// Uptime in seconds
|
||||
Uptime int64
|
||||
// Memory usage in bytes
|
||||
Memory uint64
|
||||
// Threads aka go routines
|
||||
Threads uint64
|
||||
// Garbage collection in nanoseconds
|
||||
GC uint64
|
||||
// Total requests
|
||||
Requests uint64
|
||||
// Total errors
|
||||
Errors uint64
|
||||
}
|
203
errors/errors.go
203
errors/errors.go
@@ -1,57 +1,80 @@
|
||||
// Package errors provides a way to return detailed information
|
||||
// for an RPC request error. The error is normally JSON encoded.
|
||||
package errors
|
||||
package errors // import "go.unistack.org/micro/v3/errors"
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrBadRequest
|
||||
// ErrBadRequest returns then requests contains invalid data
|
||||
ErrBadRequest = &Error{Code: 400}
|
||||
// ErrUnauthorized
|
||||
// ErrUnauthorized returns then user have unauthorized call
|
||||
ErrUnauthorized = &Error{Code: 401}
|
||||
// ErrForbidden
|
||||
// ErrForbidden returns then user have not access the resource
|
||||
ErrForbidden = &Error{Code: 403}
|
||||
// ErrNotFound
|
||||
// ErrNotFound returns then user specify invalid endpoint
|
||||
ErrNotFound = &Error{Code: 404}
|
||||
// ErrMethodNotAllowed
|
||||
// ErrMethodNotAllowed returns then user try to get invalid method
|
||||
ErrMethodNotAllowed = &Error{Code: 405}
|
||||
// ErrTimeout
|
||||
// ErrTimeout returns then timeout exceeded
|
||||
ErrTimeout = &Error{Code: 408}
|
||||
// ErrConflict
|
||||
// ErrConflict returns then request create duplicate resource
|
||||
ErrConflict = &Error{Code: 409}
|
||||
// ErrInternalServerError
|
||||
// ErrInternalServerError returns then server cant process request because of internal error
|
||||
ErrInternalServerError = &Error{Code: 500}
|
||||
// ErNotImplemented
|
||||
// ErNotImplemented returns then server does not have desired endpoint method
|
||||
ErNotImplemented = &Error{Code: 501}
|
||||
// ErrBadGateway
|
||||
// ErrBadGateway returns then server cant process request
|
||||
ErrBadGateway = &Error{Code: 502}
|
||||
// ErrServiceUnavailable
|
||||
// ErrServiceUnavailable returns then service unavailable
|
||||
ErrServiceUnavailable = &Error{Code: 503}
|
||||
// ErrGatewayTimeout
|
||||
// ErrGatewayTimeout returns then server have long time to process request
|
||||
ErrGatewayTimeout = &Error{Code: 504}
|
||||
)
|
||||
|
||||
// Error tpye
|
||||
// Error type
|
||||
type Error struct {
|
||||
Id string
|
||||
Code int32
|
||||
// ID holds error id or service, usually someting like my_service or id
|
||||
ID string
|
||||
// Detail holds some useful details about error
|
||||
Detail string
|
||||
// Status usually holds text of http status
|
||||
Status string
|
||||
// Code holds error code
|
||||
Code int32
|
||||
}
|
||||
|
||||
// Error satisfies error interface
|
||||
func (e *Error) Error() string {
|
||||
b, _ := json.Marshal(e)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// New generates a custom error.
|
||||
/*
|
||||
// Generator struct holds id of error
|
||||
type Generator struct {
|
||||
id string
|
||||
}
|
||||
|
||||
// Generator can emit new error with static id
|
||||
func NewGenerator(id string) *Generator {
|
||||
return &Generator{id: id}
|
||||
}
|
||||
|
||||
func (g *Generator) BadRequest(format string, args ...interface{}) error {
|
||||
return BadRequest(g.id, format, args...)
|
||||
}
|
||||
*/
|
||||
|
||||
// New generates a custom error
|
||||
func New(id, detail string, code int32) error {
|
||||
return &Error{
|
||||
Id: id,
|
||||
ID: id,
|
||||
Code: code,
|
||||
Detail: detail,
|
||||
Status: http.StatusText(int(code)),
|
||||
@@ -61,130 +84,130 @@ func New(id, detail string, code int32) error {
|
||||
// Parse tries to parse a JSON string into an error. If that
|
||||
// fails, it will set the given string as the error detail.
|
||||
func Parse(err string) *Error {
|
||||
e := new(Error)
|
||||
errr := json.Unmarshal([]byte(err), e)
|
||||
if errr != nil {
|
||||
e := &Error{}
|
||||
nerr := json.Unmarshal([]byte(err), e)
|
||||
if nerr != nil {
|
||||
e.Detail = err
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
// BadRequest generates a 400 error.
|
||||
func BadRequest(id, format string, a ...interface{}) error {
|
||||
func BadRequest(id, format string, args ...interface{}) error {
|
||||
return &Error{
|
||||
Id: id,
|
||||
ID: id,
|
||||
Code: 400,
|
||||
Detail: fmt.Sprintf(format, a...),
|
||||
Detail: fmt.Sprintf(format, args...),
|
||||
Status: http.StatusText(400),
|
||||
}
|
||||
}
|
||||
|
||||
// Unauthorized generates a 401 error.
|
||||
func Unauthorized(id, format string, a ...interface{}) error {
|
||||
func Unauthorized(id, format string, args ...interface{}) error {
|
||||
return &Error{
|
||||
Id: id,
|
||||
ID: id,
|
||||
Code: 401,
|
||||
Detail: fmt.Sprintf(format, a...),
|
||||
Detail: fmt.Sprintf(format, args...),
|
||||
Status: http.StatusText(401),
|
||||
}
|
||||
}
|
||||
|
||||
// Forbidden generates a 403 error.
|
||||
func Forbidden(id, format string, a ...interface{}) error {
|
||||
func Forbidden(id, format string, args ...interface{}) error {
|
||||
return &Error{
|
||||
Id: id,
|
||||
ID: id,
|
||||
Code: 403,
|
||||
Detail: fmt.Sprintf(format, a...),
|
||||
Detail: fmt.Sprintf(format, args...),
|
||||
Status: http.StatusText(403),
|
||||
}
|
||||
}
|
||||
|
||||
// NotFound generates a 404 error.
|
||||
func NotFound(id, format string, a ...interface{}) error {
|
||||
func NotFound(id, format string, args ...interface{}) error {
|
||||
return &Error{
|
||||
Id: id,
|
||||
ID: id,
|
||||
Code: 404,
|
||||
Detail: fmt.Sprintf(format, a...),
|
||||
Detail: fmt.Sprintf(format, args...),
|
||||
Status: http.StatusText(404),
|
||||
}
|
||||
}
|
||||
|
||||
// MethodNotAllowed generates a 405 error.
|
||||
func MethodNotAllowed(id, format string, a ...interface{}) error {
|
||||
func MethodNotAllowed(id, format string, args ...interface{}) error {
|
||||
return &Error{
|
||||
Id: id,
|
||||
ID: id,
|
||||
Code: 405,
|
||||
Detail: fmt.Sprintf(format, a...),
|
||||
Detail: fmt.Sprintf(format, args...),
|
||||
Status: http.StatusText(405),
|
||||
}
|
||||
}
|
||||
|
||||
// Timeout generates a 408 error.
|
||||
func Timeout(id, format string, a ...interface{}) error {
|
||||
func Timeout(id, format string, args ...interface{}) error {
|
||||
return &Error{
|
||||
Id: id,
|
||||
ID: id,
|
||||
Code: 408,
|
||||
Detail: fmt.Sprintf(format, a...),
|
||||
Detail: fmt.Sprintf(format, args...),
|
||||
Status: http.StatusText(408),
|
||||
}
|
||||
}
|
||||
|
||||
// Conflict generates a 409 error.
|
||||
func Conflict(id, format string, a ...interface{}) error {
|
||||
func Conflict(id, format string, args ...interface{}) error {
|
||||
return &Error{
|
||||
Id: id,
|
||||
ID: id,
|
||||
Code: 409,
|
||||
Detail: fmt.Sprintf(format, a...),
|
||||
Detail: fmt.Sprintf(format, args...),
|
||||
Status: http.StatusText(409),
|
||||
}
|
||||
}
|
||||
|
||||
// InternalServerError generates a 500 error.
|
||||
func InternalServerError(id, format string, a ...interface{}) error {
|
||||
func InternalServerError(id, format string, args ...interface{}) error {
|
||||
return &Error{
|
||||
Id: id,
|
||||
ID: id,
|
||||
Code: 500,
|
||||
Detail: fmt.Sprintf(format, a...),
|
||||
Detail: fmt.Sprintf(format, args...),
|
||||
Status: http.StatusText(500),
|
||||
}
|
||||
}
|
||||
|
||||
// NotImplemented generates a 501 error
|
||||
func NotImplemented(id, format string, a ...interface{}) error {
|
||||
func NotImplemented(id, format string, args ...interface{}) error {
|
||||
return &Error{
|
||||
Id: id,
|
||||
ID: id,
|
||||
Code: 501,
|
||||
Detail: fmt.Sprintf(format, a...),
|
||||
Detail: fmt.Sprintf(format, args...),
|
||||
Status: http.StatusText(501),
|
||||
}
|
||||
}
|
||||
|
||||
// BadGateway generates a 502 error
|
||||
func BadGateway(id, format string, a ...interface{}) error {
|
||||
func BadGateway(id, format string, args ...interface{}) error {
|
||||
return &Error{
|
||||
Id: id,
|
||||
ID: id,
|
||||
Code: 502,
|
||||
Detail: fmt.Sprintf(format, a...),
|
||||
Detail: fmt.Sprintf(format, args...),
|
||||
Status: http.StatusText(502),
|
||||
}
|
||||
}
|
||||
|
||||
// ServiceUnavailable generates a 503 error
|
||||
func ServiceUnavailable(id, format string, a ...interface{}) error {
|
||||
func ServiceUnavailable(id, format string, args ...interface{}) error {
|
||||
return &Error{
|
||||
Id: id,
|
||||
ID: id,
|
||||
Code: 503,
|
||||
Detail: fmt.Sprintf(format, a...),
|
||||
Detail: fmt.Sprintf(format, args...),
|
||||
Status: http.StatusText(503),
|
||||
}
|
||||
}
|
||||
|
||||
// GatewayTimeout generates a 504 error
|
||||
func GatewayTimeout(id, format string, a ...interface{}) error {
|
||||
func GatewayTimeout(id, format string, args ...interface{}) error {
|
||||
return &Error{
|
||||
Id: id,
|
||||
ID: id,
|
||||
Code: 504,
|
||||
Detail: fmt.Sprintf(format, a...),
|
||||
Detail: fmt.Sprintf(format, args...),
|
||||
Status: http.StatusText(504),
|
||||
}
|
||||
}
|
||||
@@ -217,3 +240,69 @@ func FromError(err error) *Error {
|
||||
|
||||
return Parse(err.Error())
|
||||
}
|
||||
|
||||
// MarshalJSON returns error data
|
||||
func (e *Error) MarshalJSON() ([]byte, error) {
|
||||
return e.Marshal()
|
||||
}
|
||||
|
||||
// UnmarshalJSON set error data
|
||||
func (e *Error) UnmarshalJSON(data []byte) error {
|
||||
return e.Unmarshal(data)
|
||||
}
|
||||
|
||||
// ProtoMessage noop func
|
||||
func (e *Error) ProtoMessage() {}
|
||||
|
||||
// Reset resets error
|
||||
func (e *Error) Reset() {
|
||||
*e = Error{}
|
||||
}
|
||||
|
||||
// String returns error as string
|
||||
func (e *Error) String() string {
|
||||
return fmt.Sprintf(`{"id":"%s","detail":"%s","status":"%s","code":%d}`, e.ID, e.Detail, e.Status, e.Code)
|
||||
}
|
||||
|
||||
// Marshal returns error data
|
||||
func (e *Error) Marshal() ([]byte, error) {
|
||||
return []byte(e.String()), nil
|
||||
}
|
||||
|
||||
// Unmarshal set error data
|
||||
func (e *Error) Unmarshal(data []byte) error {
|
||||
str := string(data)
|
||||
if len(data) < 41 {
|
||||
return fmt.Errorf("invalid data")
|
||||
}
|
||||
parts := strings.FieldsFunc(str[1:len(str)-1], func(r rune) bool {
|
||||
return r == ','
|
||||
})
|
||||
for _, part := range parts {
|
||||
nparts := strings.FieldsFunc(part, func(r rune) bool {
|
||||
return r == ':'
|
||||
})
|
||||
for idx := 0; idx < len(nparts); idx++ {
|
||||
if len(nparts[idx+1]) < 3 {
|
||||
idx++
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case nparts[idx] == `"id"`:
|
||||
e.ID = nparts[idx+1][1 : len(nparts[idx+1])-1]
|
||||
case nparts[idx] == `"detail"`:
|
||||
e.Detail = nparts[idx+1][1 : len(nparts[idx+1])-1]
|
||||
case nparts[idx] == `"status"`:
|
||||
e.Status = nparts[idx+1][1 : len(nparts[idx+1])-1]
|
||||
case nparts[idx] == `"code"`:
|
||||
c, err := strconv.ParseInt(nparts[idx+1], 10, 32)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
e.Code = int32(c)
|
||||
}
|
||||
idx++
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
31
errors/errors.proto
Normal file
31
errors/errors.proto
Normal file
@@ -0,0 +1,31 @@
|
||||
// Copyright 2021 Unistack LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
syntax = "proto3";
|
||||
|
||||
package micro.errors;
|
||||
|
||||
option cc_enable_arenas = true;
|
||||
option go_package = "go.unistack.org/micro/v3/errors;errors";
|
||||
option java_multiple_files = true;
|
||||
option java_outer_classname = "MicroErrors";
|
||||
option java_package = "micro.errors";
|
||||
option objc_class_prefix = "MERRORS";
|
||||
|
||||
message Error {
|
||||
string id = 1;
|
||||
string detail = 2;
|
||||
string status = 3;
|
||||
uint32 code = 4;
|
||||
}
|
@@ -2,22 +2,35 @@ package errors
|
||||
|
||||
import (
|
||||
er "errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestEmpty(t *testing.T) {
|
||||
msg := "test"
|
||||
var err *Error
|
||||
err = FromError(fmt.Errorf(msg))
|
||||
if err.Detail != msg {
|
||||
t.Fatalf("invalid error %v", err)
|
||||
}
|
||||
err = FromError(fmt.Errorf(`{"id":"","detail":"%s","status":"%s","code":0}`, msg, msg))
|
||||
if err.Detail != msg || err.Status != msg {
|
||||
t.Fatalf("invalid error %#+v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFromError(t *testing.T) {
|
||||
err := NotFound("go.micro.test", "%s", "example")
|
||||
merr := FromError(err)
|
||||
if merr.Id != "go.micro.test" || merr.Code != 404 {
|
||||
if merr.ID != "go.micro.test" || merr.Code != 404 {
|
||||
t.Fatalf("invalid conversation %v != %v", err, merr)
|
||||
}
|
||||
err = er.New(err.Error())
|
||||
merr = FromError(err)
|
||||
if merr.Id != "go.micro.test" || merr.Code != 404 {
|
||||
if merr.ID != "go.micro.test" || merr.Code != 404 {
|
||||
t.Fatalf("invalid conversation %v != %v", err, merr)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestEqual(t *testing.T) {
|
||||
@@ -32,13 +45,12 @@ func TestEqual(t *testing.T) {
|
||||
if Equal(err1, err3) {
|
||||
t.Fatal("errors must be not equal")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestErrors(t *testing.T) {
|
||||
testData := []*Error{
|
||||
{
|
||||
Id: "test",
|
||||
ID: "test",
|
||||
Code: 500,
|
||||
Detail: "Internal server error",
|
||||
Status: http.StatusText(500),
|
||||
@@ -46,7 +58,7 @@ func TestErrors(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, e := range testData {
|
||||
ne := New(e.Id, e.Detail, e.Code)
|
||||
ne := New(e.ID, e.Detail, e.Code)
|
||||
|
||||
if e.Error() != ne.Error() {
|
||||
t.Fatalf("Expected %s got %s", e.Error(), ne.Error())
|
||||
@@ -58,8 +70,8 @@ func TestErrors(t *testing.T) {
|
||||
t.Fatalf("Expected error got nil %v", pe)
|
||||
}
|
||||
|
||||
if pe.Id != e.Id {
|
||||
t.Fatalf("Expected %s got %s", e.Id, pe.Id)
|
||||
if pe.ID != e.ID {
|
||||
t.Fatalf("Expected %s got %s", e.ID, pe.ID)
|
||||
}
|
||||
|
||||
if pe.Detail != e.Detail {
|
||||
|
2
event.go
2
event.go
@@ -3,7 +3,7 @@ package micro
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/unistack-org/micro/v3/client"
|
||||
"go.unistack.org/micro/v3/client"
|
||||
)
|
||||
|
||||
// Event is used to publish messages to a topic
|
||||
|
@@ -1,49 +0,0 @@
|
||||
// Package events contains interfaces for managing events within distributed systems
|
||||
package events
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/unistack-org/micro/v3/metadata"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrMissingTopic is returned if a blank topic was provided to publish
|
||||
ErrMissingTopic = errors.New("Missing topic")
|
||||
// ErrEncodingMessage is returned from publish if there was an error encoding the message option
|
||||
ErrEncodingMessage = errors.New("Error encoding message")
|
||||
)
|
||||
|
||||
// Stream of events
|
||||
type Stream interface {
|
||||
Publish(ctx context.Context, topic string, msg interface{}, opts ...PublishOption) error
|
||||
Subscribe(ctx context.Context, topic string, opts ...SubscribeOption) (<-chan Event, error)
|
||||
}
|
||||
|
||||
// Store of events
|
||||
type Store interface {
|
||||
Read(ctx context.Context, opts ...ReadOption) ([]*Event, error)
|
||||
Write(ctx context.Context, event *Event, opts ...WriteOption) error
|
||||
}
|
||||
|
||||
// Event is the object returned by the broker when you subscribe to a topic
|
||||
type Event struct {
|
||||
// ID to uniquely identify the event
|
||||
ID string
|
||||
// Topic of event, e.g. "register.service.created"
|
||||
Topic string
|
||||
// Timestamp of the event
|
||||
Timestamp time.Time
|
||||
// Metadata contains the encoded event was indexed by
|
||||
Metadata metadata.Metadata
|
||||
// Payload contains the encoded message
|
||||
Payload []byte
|
||||
}
|
||||
|
||||
// Unmarshal the events message into an object
|
||||
func (e *Event) Unmarshal(v interface{}) error {
|
||||
return json.Unmarshal(e.Payload, v)
|
||||
}
|
@@ -1,124 +0,0 @@
|
||||
package events
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/unistack-org/micro/v3/metadata"
|
||||
)
|
||||
|
||||
// PublishOptions contains all the options which can be provided when publishing an event
|
||||
type PublishOptions struct {
|
||||
// Metadata contains any keys which can be used to query the data, for example a customer id
|
||||
Metadata metadata.Metadata
|
||||
// Timestamp to set for the event, if the timestamp is a zero value, the current time will be used
|
||||
Timestamp time.Time
|
||||
}
|
||||
|
||||
// PublishOption sets attributes on PublishOptions
|
||||
type PublishOption func(o *PublishOptions)
|
||||
|
||||
// WithMetadata sets the Metadata field on PublishOptions
|
||||
func WithMetadata(md metadata.Metadata) PublishOption {
|
||||
return func(o *PublishOptions) {
|
||||
o.Metadata = metadata.Copy(md)
|
||||
}
|
||||
}
|
||||
|
||||
// WithTimestamp sets the timestamp field on PublishOptions
|
||||
func WithTimestamp(t time.Time) PublishOption {
|
||||
return func(o *PublishOptions) {
|
||||
o.Timestamp = t
|
||||
}
|
||||
}
|
||||
|
||||
// SubscribeOptions contains all the options which can be provided when subscribing to a topic
|
||||
type SubscribeOptions struct {
|
||||
// Queue is the name of the subscribers queue, if two subscribers have the same queue the message
|
||||
// should only be published to one of them
|
||||
Queue string
|
||||
// StartAtTime is the time from which the messages should be consumed from. If not provided then
|
||||
// the messages will be consumed starting from the moment the Subscription starts.
|
||||
StartAtTime time.Time
|
||||
}
|
||||
|
||||
// SubscribeOption sets attributes on SubscribeOptions
|
||||
type SubscribeOption func(o *SubscribeOptions)
|
||||
|
||||
// WithQueue sets the Queue fielf on SubscribeOptions to the value provided
|
||||
func WithQueue(q string) SubscribeOption {
|
||||
return func(o *SubscribeOptions) {
|
||||
o.Queue = q
|
||||
}
|
||||
}
|
||||
|
||||
// WithStartAtTime sets the StartAtTime field on SubscribeOptions to the value provided
|
||||
func WithStartAtTime(t time.Time) SubscribeOption {
|
||||
return func(o *SubscribeOptions) {
|
||||
o.StartAtTime = t
|
||||
}
|
||||
}
|
||||
|
||||
// WriteOptions contains all the options which can be provided when writing an event to a store
|
||||
type WriteOptions struct {
|
||||
// TTL is the duration the event should be recorded for, a zero value TTL indicates the event should
|
||||
// be stored indefinitely
|
||||
TTL time.Duration
|
||||
}
|
||||
|
||||
// WriteOption sets attributes on WriteOptions
|
||||
type WriteOption func(o *WriteOptions)
|
||||
|
||||
// WithTTL sets the TTL attribute on WriteOptions
|
||||
func WithTTL(d time.Duration) WriteOption {
|
||||
return func(o *WriteOptions) {
|
||||
o.TTL = d
|
||||
}
|
||||
}
|
||||
|
||||
// ReadOptions contains all the options which can be provided when reading events from a store
|
||||
type ReadOptions struct {
|
||||
// Topic to read events from, if no topic is provided events from all topics will be returned
|
||||
Topic string
|
||||
// Query to filter the results using. The store will query the metadata provided when the event
|
||||
// was written to the store
|
||||
Query map[string]string
|
||||
// Limit the number of results to return
|
||||
Limit int
|
||||
// Offset the results by this number, useful for paginated queries
|
||||
Offset int
|
||||
}
|
||||
|
||||
// ReadOption sets attributes on ReadOptions
|
||||
type ReadOption func(o *ReadOptions)
|
||||
|
||||
// ReadTopic sets the topic attribute on ReadOptions
|
||||
func ReadTopic(t string) ReadOption {
|
||||
return func(o *ReadOptions) {
|
||||
o.Topic = t
|
||||
}
|
||||
}
|
||||
|
||||
// ReadFilter sets a key and value in the query
|
||||
func ReadFilter(key, value string) ReadOption {
|
||||
return func(o *ReadOptions) {
|
||||
if o.Query == nil {
|
||||
o.Query = map[string]string{key: value}
|
||||
} else {
|
||||
o.Query[key] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ReadLimit sets the limit attribute on ReadOptions
|
||||
func ReadLimit(l int) ReadOption {
|
||||
return func(o *ReadOptions) {
|
||||
o.Limit = 1
|
||||
}
|
||||
}
|
||||
|
||||
// ReadOffset sets the offset attribute on ReadOptions
|
||||
func ReadOffset(l int) ReadOption {
|
||||
return func(o *ReadOptions) {
|
||||
o.Offset = 1
|
||||
}
|
||||
}
|
34
flow/context.go
Normal file
34
flow/context.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package flow
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
type flowKey struct{}
|
||||
|
||||
// FromContext returns Flow from context
|
||||
func FromContext(ctx context.Context) (Flow, bool) {
|
||||
if ctx == nil {
|
||||
return nil, false
|
||||
}
|
||||
c, ok := ctx.Value(flowKey{}).(Flow)
|
||||
return c, ok
|
||||
}
|
||||
|
||||
// NewContext stores Flow to context
|
||||
func NewContext(ctx context.Context, f Flow) context.Context {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
return context.WithValue(ctx, flowKey{}, f)
|
||||
}
|
||||
|
||||
// SetOption returns a function to setup a context with given value
|
||||
func SetOption(k, v interface{}) Option {
|
||||
return func(o *Options) {
|
||||
if o.Context == nil {
|
||||
o.Context = context.Background()
|
||||
}
|
||||
o.Context = context.WithValue(o.Context, k, v)
|
||||
}
|
||||
}
|
21
flow/dag.go
Normal file
21
flow/dag.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package flow
|
||||
|
||||
type node struct {
|
||||
name string
|
||||
}
|
||||
|
||||
func (n *node) ID() string {
|
||||
return n.name
|
||||
}
|
||||
|
||||
func (n *node) Name() string {
|
||||
return n.name
|
||||
}
|
||||
|
||||
func (n *node) String() string {
|
||||
return n.name
|
||||
}
|
||||
|
||||
func (n *node) Hashcode() interface{} {
|
||||
return n.name
|
||||
}
|
68
flow/dag_test.go
Normal file
68
flow/dag_test.go
Normal file
@@ -0,0 +1,68 @@
|
||||
package flow
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/silas/dag"
|
||||
)
|
||||
|
||||
func checkErr(t *testing.T, err error) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDag(t *testing.T) {
|
||||
d1 := &dag.AcyclicGraph{}
|
||||
d2 := &dag.AcyclicGraph{}
|
||||
d2v1 := d2.Add(&node{"Substep.Create"})
|
||||
v1 := d1.Add(&node{"AccountService.Create"})
|
||||
v2 := d1.Add(&node{"AuthzService.Create"})
|
||||
v3 := d1.Add(&node{"AuthnService.Create"})
|
||||
v4 := d1.Add(&node{"ProjectService.Create"})
|
||||
v5 := d1.Add(&node{"ContactService.Create"})
|
||||
v6 := d1.Add(&node{"NetworkService.Create"})
|
||||
v7 := d1.Add(&node{"MailerService.Create"})
|
||||
v8 := d1.Add(&node{"NestedService.Create"})
|
||||
v9 := d1.Add(d2v1)
|
||||
d1.Connect(dag.BasicEdge(v1, v2))
|
||||
d1.Connect(dag.BasicEdge(v1, v3))
|
||||
d1.Connect(dag.BasicEdge(v1, v4))
|
||||
d1.Connect(dag.BasicEdge(v1, v5))
|
||||
d1.Connect(dag.BasicEdge(v1, v6))
|
||||
d1.Connect(dag.BasicEdge(v1, v7))
|
||||
d1.Connect(dag.BasicEdge(v7, v8))
|
||||
d1.Connect(dag.BasicEdge(v8, v9))
|
||||
|
||||
if err := d1.Validate(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
d1.TransitiveReduction()
|
||||
|
||||
var steps [][]string
|
||||
fn := func(n dag.Vertex, idx int) error {
|
||||
if idx == 0 {
|
||||
steps = make([][]string, 1)
|
||||
steps[0] = make([]string, 0, 1)
|
||||
} else if idx >= len(steps) {
|
||||
tsteps := make([][]string, idx+1)
|
||||
copy(tsteps, steps)
|
||||
steps = tsteps
|
||||
steps[idx] = make([]string, 0, 1)
|
||||
}
|
||||
steps[idx] = append(steps[idx], fmt.Sprintf("%s", n))
|
||||
return nil
|
||||
}
|
||||
|
||||
start := &node{"AccountService.Create"}
|
||||
err := d1.SortedDepthFirstWalk([]dag.Vertex{start}, fn)
|
||||
checkErr(t, err)
|
||||
if len(steps) != 4 {
|
||||
t.Fatalf("invalid steps: %#+v", steps)
|
||||
}
|
||||
if steps[3][0] != "Substep.Create" {
|
||||
t.Fatalf("invalid last step: %#+v", steps)
|
||||
}
|
||||
}
|
588
flow/default.go
Normal file
588
flow/default.go
Normal file
@@ -0,0 +1,588 @@
|
||||
package flow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
|
||||
"github.com/silas/dag"
|
||||
"go.unistack.org/micro/v3/client"
|
||||
"go.unistack.org/micro/v3/codec"
|
||||
"go.unistack.org/micro/v3/logger"
|
||||
"go.unistack.org/micro/v3/metadata"
|
||||
"go.unistack.org/micro/v3/store"
|
||||
"go.unistack.org/micro/v3/util/id"
|
||||
)
|
||||
|
||||
type microFlow struct {
|
||||
opts Options
|
||||
}
|
||||
|
||||
type microWorkflow struct {
|
||||
opts Options
|
||||
g *dag.AcyclicGraph
|
||||
steps map[string]Step
|
||||
id string
|
||||
status Status
|
||||
sync.RWMutex
|
||||
init bool
|
||||
}
|
||||
|
||||
func (w *microWorkflow) ID() string {
|
||||
return w.id
|
||||
}
|
||||
|
||||
func (w *microWorkflow) Steps() ([][]Step, error) {
|
||||
return w.getSteps("", false)
|
||||
}
|
||||
|
||||
func (w *microWorkflow) Status() Status {
|
||||
return w.status
|
||||
}
|
||||
|
||||
func (w *microWorkflow) AppendSteps(steps ...Step) error {
|
||||
w.Lock()
|
||||
|
||||
for _, s := range steps {
|
||||
w.steps[s.String()] = s
|
||||
w.g.Add(s)
|
||||
}
|
||||
|
||||
for _, dst := range steps {
|
||||
for _, req := range dst.Requires() {
|
||||
src, ok := w.steps[req]
|
||||
if !ok {
|
||||
return ErrStepNotExists
|
||||
}
|
||||
w.g.Connect(dag.BasicEdge(src, dst))
|
||||
}
|
||||
}
|
||||
|
||||
if err := w.g.Validate(); err != nil {
|
||||
w.Unlock()
|
||||
return err
|
||||
}
|
||||
|
||||
w.g.TransitiveReduction()
|
||||
|
||||
w.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *microWorkflow) RemoveSteps(steps ...Step) error {
|
||||
// TODO: handle case when some step requires or required by removed step
|
||||
|
||||
w.Lock()
|
||||
|
||||
for _, s := range steps {
|
||||
delete(w.steps, s.String())
|
||||
w.g.Remove(s)
|
||||
}
|
||||
|
||||
for _, dst := range steps {
|
||||
for _, req := range dst.Requires() {
|
||||
src, ok := w.steps[req]
|
||||
if !ok {
|
||||
return ErrStepNotExists
|
||||
}
|
||||
w.g.Connect(dag.BasicEdge(src, dst))
|
||||
}
|
||||
}
|
||||
|
||||
if err := w.g.Validate(); err != nil {
|
||||
w.Unlock()
|
||||
return err
|
||||
}
|
||||
|
||||
w.g.TransitiveReduction()
|
||||
|
||||
w.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *microWorkflow) getSteps(start string, reverse bool) ([][]Step, error) {
|
||||
var steps [][]Step
|
||||
var root dag.Vertex
|
||||
var err error
|
||||
|
||||
fn := func(n dag.Vertex, idx int) error {
|
||||
if idx == 0 {
|
||||
steps = make([][]Step, 1)
|
||||
steps[0] = make([]Step, 0, 1)
|
||||
} else if idx >= len(steps) {
|
||||
tsteps := make([][]Step, idx+1)
|
||||
copy(tsteps, steps)
|
||||
steps = tsteps
|
||||
steps[idx] = make([]Step, 0, 1)
|
||||
}
|
||||
steps[idx] = append(steps[idx], n.(Step))
|
||||
return nil
|
||||
}
|
||||
|
||||
if start != "" {
|
||||
var ok bool
|
||||
w.RLock()
|
||||
root, ok = w.steps[start]
|
||||
w.RUnlock()
|
||||
if !ok {
|
||||
return nil, ErrStepNotExists
|
||||
}
|
||||
} else {
|
||||
root, err = w.g.Root()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if reverse {
|
||||
err = w.g.SortedReverseDepthFirstWalk([]dag.Vertex{root}, fn)
|
||||
} else {
|
||||
err = w.g.SortedDepthFirstWalk([]dag.Vertex{root}, fn)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return steps, nil
|
||||
}
|
||||
|
||||
func (w *microWorkflow) Abort(ctx context.Context, id string) error {
|
||||
workflowStore := store.NewNamespaceStore(w.opts.Store, filepath.Join("workflows", id))
|
||||
return workflowStore.Write(ctx, "status", &codec.Frame{Data: []byte(StatusAborted.String())})
|
||||
}
|
||||
|
||||
func (w *microWorkflow) Suspend(ctx context.Context, id string) error {
|
||||
workflowStore := store.NewNamespaceStore(w.opts.Store, filepath.Join("workflows", id))
|
||||
return workflowStore.Write(ctx, "status", &codec.Frame{Data: []byte(StatusSuspend.String())})
|
||||
}
|
||||
|
||||
func (w *microWorkflow) Resume(ctx context.Context, id string) error {
|
||||
workflowStore := store.NewNamespaceStore(w.opts.Store, filepath.Join("workflows", id))
|
||||
return workflowStore.Write(ctx, "status", &codec.Frame{Data: []byte(StatusRunning.String())})
|
||||
}
|
||||
|
||||
func (w *microWorkflow) Execute(ctx context.Context, req *Message, opts ...ExecuteOption) (string, error) {
|
||||
w.Lock()
|
||||
if !w.init {
|
||||
if err := w.g.Validate(); err != nil {
|
||||
w.Unlock()
|
||||
return "", err
|
||||
}
|
||||
w.g.TransitiveReduction()
|
||||
w.init = true
|
||||
}
|
||||
w.Unlock()
|
||||
|
||||
eid, err := id.New()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
stepStore := store.NewNamespaceStore(w.opts.Store, filepath.Join("steps", eid))
|
||||
workflowStore := store.NewNamespaceStore(w.opts.Store, filepath.Join("workflows", eid))
|
||||
|
||||
options := NewExecuteOptions(opts...)
|
||||
|
||||
steps, err := w.getSteps(options.Start, options.Reverse)
|
||||
if err != nil {
|
||||
if werr := workflowStore.Write(w.opts.Context, "status", &codec.Frame{Data: []byte(StatusPending.String())}); werr != nil {
|
||||
w.opts.Logger.Errorf(w.opts.Context, "store error: %v", werr)
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
cherr := make(chan error, 1)
|
||||
chstatus := make(chan Status, 1)
|
||||
|
||||
nctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
|
||||
nopts := make([]ExecuteOption, 0, len(opts)+5)
|
||||
|
||||
nopts = append(nopts,
|
||||
ExecuteClient(w.opts.Client),
|
||||
ExecuteTracer(w.opts.Tracer),
|
||||
ExecuteLogger(w.opts.Logger),
|
||||
ExecuteMeter(w.opts.Meter),
|
||||
)
|
||||
nopts = append(nopts, opts...)
|
||||
done := make(chan struct{})
|
||||
|
||||
if werr := workflowStore.Write(w.opts.Context, "status", &codec.Frame{Data: []byte(StatusRunning.String())}); werr != nil {
|
||||
w.opts.Logger.Errorf(w.opts.Context, "store error: %v", werr)
|
||||
return eid, werr
|
||||
}
|
||||
for idx := range steps {
|
||||
for nidx := range steps[idx] {
|
||||
cstep := steps[idx][nidx]
|
||||
if werr := stepStore.Write(ctx, filepath.Join(cstep.ID(), "status"), &codec.Frame{Data: []byte(StatusPending.String())}); werr != nil {
|
||||
return eid, werr
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
go func() {
|
||||
for idx := range steps {
|
||||
for nidx := range steps[idx] {
|
||||
wStatus := &codec.Frame{}
|
||||
if werr := workflowStore.Read(w.opts.Context, "status", wStatus); werr != nil {
|
||||
cherr <- werr
|
||||
return
|
||||
}
|
||||
if status := StringStatus[string(wStatus.Data)]; status != StatusRunning {
|
||||
chstatus <- status
|
||||
return
|
||||
}
|
||||
if w.opts.Logger.V(logger.TraceLevel) {
|
||||
w.opts.Logger.Tracef(nctx, "will be executed %v", steps[idx][nidx])
|
||||
}
|
||||
cstep := steps[idx][nidx]
|
||||
// nolint: nestif
|
||||
if len(cstep.Requires()) == 0 {
|
||||
wg.Add(1)
|
||||
go func(step Step) {
|
||||
defer wg.Done()
|
||||
if werr := stepStore.Write(ctx, filepath.Join(step.ID(), "req"), req); werr != nil {
|
||||
cherr <- werr
|
||||
return
|
||||
}
|
||||
if werr := stepStore.Write(ctx, filepath.Join(step.ID(), "status"), &codec.Frame{Data: []byte(StatusRunning.String())}); werr != nil {
|
||||
cherr <- werr
|
||||
return
|
||||
}
|
||||
rsp, serr := step.Execute(nctx, req, nopts...)
|
||||
if serr != nil {
|
||||
step.SetStatus(StatusFailure)
|
||||
if werr := stepStore.Write(ctx, filepath.Join(step.ID(), "rsp"), serr); werr != nil && w.opts.Logger.V(logger.ErrorLevel) {
|
||||
w.opts.Logger.Errorf(ctx, "store write error: %v", werr)
|
||||
}
|
||||
if werr := stepStore.Write(ctx, filepath.Join(step.ID(), "status"), &codec.Frame{Data: []byte(StatusFailure.String())}); werr != nil && w.opts.Logger.V(logger.ErrorLevel) {
|
||||
w.opts.Logger.Errorf(ctx, "store write error: %v", werr)
|
||||
}
|
||||
cherr <- serr
|
||||
return
|
||||
}
|
||||
if werr := stepStore.Write(ctx, filepath.Join(step.ID(), "rsp"), rsp); werr != nil {
|
||||
w.opts.Logger.Errorf(ctx, "store write error: %v", werr)
|
||||
cherr <- werr
|
||||
return
|
||||
}
|
||||
if werr := stepStore.Write(ctx, filepath.Join(step.ID(), "status"), &codec.Frame{Data: []byte(StatusSuccess.String())}); werr != nil {
|
||||
w.opts.Logger.Errorf(ctx, "store write error: %v", werr)
|
||||
cherr <- werr
|
||||
return
|
||||
}
|
||||
}(cstep)
|
||||
wg.Wait()
|
||||
} else {
|
||||
if werr := stepStore.Write(ctx, filepath.Join(cstep.ID(), "req"), req); werr != nil {
|
||||
cherr <- werr
|
||||
return
|
||||
}
|
||||
if werr := stepStore.Write(ctx, filepath.Join(cstep.ID(), "status"), &codec.Frame{Data: []byte(StatusRunning.String())}); werr != nil {
|
||||
cherr <- werr
|
||||
return
|
||||
}
|
||||
rsp, serr := cstep.Execute(nctx, req, nopts...)
|
||||
if serr != nil {
|
||||
cstep.SetStatus(StatusFailure)
|
||||
if werr := stepStore.Write(ctx, filepath.Join(cstep.ID(), "rsp"), serr); werr != nil && w.opts.Logger.V(logger.ErrorLevel) {
|
||||
w.opts.Logger.Errorf(ctx, "store write error: %v", werr)
|
||||
}
|
||||
if werr := stepStore.Write(ctx, filepath.Join(cstep.ID(), "status"), &codec.Frame{Data: []byte(StatusFailure.String())}); werr != nil && w.opts.Logger.V(logger.ErrorLevel) {
|
||||
w.opts.Logger.Errorf(ctx, "store write error: %v", werr)
|
||||
}
|
||||
cherr <- serr
|
||||
return
|
||||
}
|
||||
if werr := stepStore.Write(ctx, filepath.Join(cstep.ID(), "rsp"), rsp); werr != nil {
|
||||
w.opts.Logger.Errorf(ctx, "store write error: %v", werr)
|
||||
cherr <- werr
|
||||
return
|
||||
}
|
||||
if werr := stepStore.Write(ctx, filepath.Join(cstep.ID(), "status"), &codec.Frame{Data: []byte(StatusSuccess.String())}); werr != nil {
|
||||
cherr <- werr
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
close(done)
|
||||
}()
|
||||
|
||||
if options.Async {
|
||||
return eid, nil
|
||||
}
|
||||
|
||||
logger.Tracef(ctx, "wait for finish or error")
|
||||
select {
|
||||
case <-nctx.Done():
|
||||
err = nctx.Err()
|
||||
case cerr := <-cherr:
|
||||
err = cerr
|
||||
case <-done:
|
||||
close(cherr)
|
||||
case <-chstatus:
|
||||
close(chstatus)
|
||||
return eid, nil
|
||||
}
|
||||
|
||||
switch {
|
||||
case nctx.Err() != nil:
|
||||
if werr := workflowStore.Write(w.opts.Context, "status", &codec.Frame{Data: []byte(StatusAborted.String())}); werr != nil {
|
||||
w.opts.Logger.Errorf(w.opts.Context, "store error: %v", werr)
|
||||
}
|
||||
case err == nil:
|
||||
if werr := workflowStore.Write(w.opts.Context, "status", &codec.Frame{Data: []byte(StatusSuccess.String())}); werr != nil {
|
||||
w.opts.Logger.Errorf(w.opts.Context, "store error: %v", werr)
|
||||
}
|
||||
case err != nil:
|
||||
if werr := workflowStore.Write(w.opts.Context, "status", &codec.Frame{Data: []byte(StatusFailure.String())}); werr != nil {
|
||||
w.opts.Logger.Errorf(w.opts.Context, "store error: %v", werr)
|
||||
}
|
||||
}
|
||||
|
||||
return eid, err
|
||||
}
|
||||
|
||||
// NewFlow create new flow
|
||||
func NewFlow(opts ...Option) Flow {
|
||||
options := NewOptions(opts...)
|
||||
return µFlow{opts: options}
|
||||
}
|
||||
|
||||
func (f *microFlow) Options() Options {
|
||||
return f.opts
|
||||
}
|
||||
|
||||
func (f *microFlow) Init(opts ...Option) error {
|
||||
for _, o := range opts {
|
||||
o(&f.opts)
|
||||
}
|
||||
if err := f.opts.Client.Init(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := f.opts.Tracer.Init(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := f.opts.Logger.Init(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := f.opts.Meter.Init(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := f.opts.Store.Init(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *microFlow) WorkflowList(ctx context.Context) ([]Workflow, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (f *microFlow) WorkflowCreate(ctx context.Context, id string, steps ...Step) (Workflow, error) {
|
||||
w := µWorkflow{opts: f.opts, id: id, g: &dag.AcyclicGraph{}, steps: make(map[string]Step, len(steps))}
|
||||
|
||||
for _, s := range steps {
|
||||
w.steps[s.String()] = s
|
||||
w.g.Add(s)
|
||||
}
|
||||
|
||||
for _, dst := range steps {
|
||||
for _, req := range dst.Requires() {
|
||||
src, ok := w.steps[req]
|
||||
if !ok {
|
||||
return nil, ErrStepNotExists
|
||||
}
|
||||
w.g.Connect(dag.BasicEdge(src, dst))
|
||||
}
|
||||
}
|
||||
|
||||
if err := w.g.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
w.g.TransitiveReduction()
|
||||
|
||||
w.init = true
|
||||
|
||||
return w, nil
|
||||
}
|
||||
|
||||
func (f *microFlow) WorkflowRemove(ctx context.Context, id string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *microFlow) WorkflowSave(ctx context.Context, w Workflow) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *microFlow) WorkflowLoad(ctx context.Context, id string) (Workflow, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
type microCallStep struct {
|
||||
rsp *Message
|
||||
req *Message
|
||||
service string
|
||||
method string
|
||||
opts StepOptions
|
||||
status Status
|
||||
}
|
||||
|
||||
func (s *microCallStep) Request() *Message {
|
||||
return s.req
|
||||
}
|
||||
|
||||
func (s *microCallStep) Response() *Message {
|
||||
return s.rsp
|
||||
}
|
||||
|
||||
func (s *microCallStep) ID() string {
|
||||
return s.String()
|
||||
}
|
||||
|
||||
func (s *microCallStep) Options() StepOptions {
|
||||
return s.opts
|
||||
}
|
||||
|
||||
func (s *microCallStep) Endpoint() string {
|
||||
return s.method
|
||||
}
|
||||
|
||||
func (s *microCallStep) Requires() []string {
|
||||
return s.opts.Requires
|
||||
}
|
||||
|
||||
func (s *microCallStep) Require(steps ...Step) error {
|
||||
for _, step := range steps {
|
||||
s.opts.Requires = append(s.opts.Requires, step.String())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *microCallStep) String() string {
|
||||
if s.opts.ID != "" {
|
||||
return s.opts.ID
|
||||
}
|
||||
return fmt.Sprintf("%s.%s", s.service, s.method)
|
||||
}
|
||||
|
||||
func (s *microCallStep) Name() string {
|
||||
return s.String()
|
||||
}
|
||||
|
||||
func (s *microCallStep) Hashcode() interface{} {
|
||||
return s.String()
|
||||
}
|
||||
|
||||
func (s *microCallStep) GetStatus() Status {
|
||||
return s.status
|
||||
}
|
||||
|
||||
func (s *microCallStep) SetStatus(status Status) {
|
||||
s.status = status
|
||||
}
|
||||
|
||||
func (s *microCallStep) Execute(ctx context.Context, req *Message, opts ...ExecuteOption) (*Message, error) {
|
||||
options := NewExecuteOptions(opts...)
|
||||
if options.Client == nil {
|
||||
return nil, ErrMissingClient
|
||||
}
|
||||
rsp := &codec.Frame{}
|
||||
copts := []client.CallOption{client.WithRetries(0)}
|
||||
if options.Timeout > 0 {
|
||||
copts = append(copts,
|
||||
client.WithRequestTimeout(options.Timeout),
|
||||
client.WithDialTimeout(options.Timeout))
|
||||
}
|
||||
nctx := metadata.NewOutgoingContext(ctx, req.Header)
|
||||
err := options.Client.Call(nctx, options.Client.NewRequest(s.service, s.method, &codec.Frame{Data: req.Body}), rsp, copts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
md, _ := metadata.FromOutgoingContext(nctx)
|
||||
return &Message{Header: md, Body: rsp.Data}, err
|
||||
}
|
||||
|
||||
type microPublishStep struct {
|
||||
req *Message
|
||||
rsp *Message
|
||||
topic string
|
||||
opts StepOptions
|
||||
status Status
|
||||
}
|
||||
|
||||
func (s *microPublishStep) Request() *Message {
|
||||
return s.req
|
||||
}
|
||||
|
||||
func (s *microPublishStep) Response() *Message {
|
||||
return s.rsp
|
||||
}
|
||||
|
||||
func (s *microPublishStep) ID() string {
|
||||
return s.String()
|
||||
}
|
||||
|
||||
func (s *microPublishStep) Options() StepOptions {
|
||||
return s.opts
|
||||
}
|
||||
|
||||
func (s *microPublishStep) Endpoint() string {
|
||||
return s.topic
|
||||
}
|
||||
|
||||
func (s *microPublishStep) Requires() []string {
|
||||
return s.opts.Requires
|
||||
}
|
||||
|
||||
func (s *microPublishStep) Require(steps ...Step) error {
|
||||
for _, step := range steps {
|
||||
s.opts.Requires = append(s.opts.Requires, step.String())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *microPublishStep) String() string {
|
||||
if s.opts.ID != "" {
|
||||
return s.opts.ID
|
||||
}
|
||||
return s.topic
|
||||
}
|
||||
|
||||
func (s *microPublishStep) Name() string {
|
||||
return s.String()
|
||||
}
|
||||
|
||||
func (s *microPublishStep) Hashcode() interface{} {
|
||||
return s.String()
|
||||
}
|
||||
|
||||
func (s *microPublishStep) GetStatus() Status {
|
||||
return s.status
|
||||
}
|
||||
|
||||
func (s *microPublishStep) SetStatus(status Status) {
|
||||
s.status = status
|
||||
}
|
||||
|
||||
func (s *microPublishStep) Execute(ctx context.Context, req *Message, opts ...ExecuteOption) (*Message, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// NewCallStep create new step with client.Call
|
||||
func NewCallStep(service string, name string, method string, opts ...StepOption) Step {
|
||||
options := NewStepOptions(opts...)
|
||||
return µCallStep{service: service, method: name + "." + method, opts: options}
|
||||
}
|
||||
|
||||
// NewPublishStep create new step with client.Publish
|
||||
func NewPublishStep(topic string, opts ...StepOption) Step {
|
||||
options := NewStepOptions(opts...)
|
||||
return µPublishStep{topic: topic, opts: options}
|
||||
}
|
152
flow/flow.go
Normal file
152
flow/flow.go
Normal file
@@ -0,0 +1,152 @@
|
||||
// Package flow is an interface used for saga pattern microservice workflow
|
||||
package flow // import "go.unistack.org/micro/v3/flow"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"go.unistack.org/micro/v3/metadata"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrStepNotExists = errors.New("step not exists")
|
||||
ErrMissingClient = errors.New("client not set")
|
||||
)
|
||||
|
||||
// RawMessage is a raw encoded JSON value.
|
||||
// It implements Marshaler and Unmarshaler and can be used to delay decoding or precompute a encoding.
|
||||
type RawMessage []byte
|
||||
|
||||
// MarshalJSON returns m as the JSON encoding of m.
|
||||
func (m *RawMessage) MarshalJSON() ([]byte, error) {
|
||||
if m == nil {
|
||||
return []byte("null"), nil
|
||||
}
|
||||
return *m, nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON sets *m to a copy of data.
|
||||
func (m *RawMessage) UnmarshalJSON(data []byte) error {
|
||||
if m == nil {
|
||||
return errors.New("RawMessage UnmarshalJSON on nil pointer")
|
||||
}
|
||||
*m = append((*m)[0:0], data...)
|
||||
return nil
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
Header metadata.Metadata
|
||||
Body RawMessage
|
||||
}
|
||||
|
||||
// Step represents dedicated workflow step
|
||||
type Step interface {
|
||||
// ID returns step id
|
||||
ID() string
|
||||
// Endpoint returns rpc endpoint service_name.service_method or broker topic
|
||||
Endpoint() string
|
||||
// Execute step run
|
||||
Execute(ctx context.Context, req *Message, opts ...ExecuteOption) (*Message, error)
|
||||
// Requires returns dependent steps
|
||||
Requires() []string
|
||||
// Options returns step options
|
||||
Options() StepOptions
|
||||
// Require add required steps
|
||||
Require(steps ...Step) error
|
||||
// String
|
||||
String() string
|
||||
// GetStatus returns step status
|
||||
GetStatus() Status
|
||||
// SetStatus sets the step status
|
||||
SetStatus(Status)
|
||||
// Request returns step request message
|
||||
Request() *Message
|
||||
// Response returns step response message
|
||||
Response() *Message
|
||||
}
|
||||
|
||||
type Status int
|
||||
|
||||
func (status Status) String() string {
|
||||
return StatusString[status]
|
||||
}
|
||||
|
||||
const (
|
||||
StatusPending Status = iota
|
||||
StatusRunning
|
||||
StatusFailure
|
||||
StatusSuccess
|
||||
StatusAborted
|
||||
StatusSuspend
|
||||
)
|
||||
|
||||
var (
|
||||
StatusString = map[Status]string{
|
||||
StatusPending: "StatusPending",
|
||||
StatusRunning: "StatusRunning",
|
||||
StatusFailure: "StatusFailure",
|
||||
StatusSuccess: "StatusSuccess",
|
||||
StatusAborted: "StatusAborted",
|
||||
StatusSuspend: "StatusSuspend",
|
||||
}
|
||||
StringStatus = map[string]Status{
|
||||
"StatusPending": StatusPending,
|
||||
"StatusRunning": StatusRunning,
|
||||
"StatusFailure": StatusFailure,
|
||||
"StatusSuccess": StatusSuccess,
|
||||
"StatusAborted": StatusAborted,
|
||||
"StatusSuspend": StatusSuspend,
|
||||
}
|
||||
)
|
||||
|
||||
// Workflow contains all steps to execute
|
||||
type Workflow interface {
|
||||
// ID returns id of the workflow
|
||||
ID() string
|
||||
// Execute workflow with args, return execution id and error
|
||||
Execute(ctx context.Context, req *Message, opts ...ExecuteOption) (string, error)
|
||||
// RemoveSteps remove steps from workflow
|
||||
RemoveSteps(steps ...Step) error
|
||||
// AppendSteps append steps to workflow
|
||||
AppendSteps(steps ...Step) error
|
||||
// Status returns workflow status
|
||||
Status() Status
|
||||
// Steps returns steps slice where parallel steps returned on the same level
|
||||
Steps() ([][]Step, error)
|
||||
// Suspend suspends execution
|
||||
Suspend(ctx context.Context, id string) error
|
||||
// Resume resumes execution
|
||||
Resume(ctx context.Context, id string) error
|
||||
// Abort abort execution
|
||||
Abort(ctx context.Context, id string) error
|
||||
}
|
||||
|
||||
// Flow the base interface to interact with workflows
|
||||
type Flow interface {
|
||||
// Options returns options
|
||||
Options() Options
|
||||
// Init initialize
|
||||
Init(...Option) error
|
||||
// WorkflowCreate creates new workflow with specific id and steps
|
||||
WorkflowCreate(ctx context.Context, id string, steps ...Step) (Workflow, error)
|
||||
// WorkflowSave saves workflow
|
||||
WorkflowSave(ctx context.Context, w Workflow) error
|
||||
// WorkflowLoad loads workflow with specific id
|
||||
WorkflowLoad(ctx context.Context, id string) (Workflow, error)
|
||||
// WorkflowList lists all workflows
|
||||
WorkflowList(ctx context.Context) ([]Workflow, error)
|
||||
}
|
||||
|
||||
var (
|
||||
flowMu sync.Mutex
|
||||
atomicSteps atomic.Value
|
||||
)
|
||||
|
||||
func RegisterStep(step Step) {
|
||||
flowMu.Lock()
|
||||
steps, _ := atomicSteps.Load().([]Step)
|
||||
atomicSteps.Store(append(steps, step))
|
||||
flowMu.Unlock()
|
||||
}
|
247
flow/options.go
Normal file
247
flow/options.go
Normal file
@@ -0,0 +1,247 @@
|
||||
package flow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"go.unistack.org/micro/v3/client"
|
||||
"go.unistack.org/micro/v3/logger"
|
||||
"go.unistack.org/micro/v3/meter"
|
||||
"go.unistack.org/micro/v3/store"
|
||||
"go.unistack.org/micro/v3/tracer"
|
||||
)
|
||||
|
||||
// Option func
|
||||
type Option func(*Options)
|
||||
|
||||
// Options server struct
|
||||
type Options struct {
|
||||
// Context holds the external options and can be used for flow shutdown
|
||||
Context context.Context
|
||||
// Client holds the client.Client
|
||||
Client client.Client
|
||||
// Tracer holds the tracer
|
||||
Tracer tracer.Tracer
|
||||
// Logger holds the logger
|
||||
Logger logger.Logger
|
||||
// Meter holds the meter
|
||||
Meter meter.Meter
|
||||
// Store used for intermediate results
|
||||
Store store.Store
|
||||
}
|
||||
|
||||
// NewOptions returns new options struct with default or passed values
|
||||
func NewOptions(opts ...Option) Options {
|
||||
options := Options{
|
||||
Context: context.Background(),
|
||||
Logger: logger.DefaultLogger,
|
||||
Meter: meter.DefaultMeter,
|
||||
Tracer: tracer.DefaultTracer,
|
||||
Client: client.DefaultClient,
|
||||
}
|
||||
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
// Logger sets the logger option
|
||||
func Logger(l logger.Logger) Option {
|
||||
return func(o *Options) {
|
||||
o.Logger = l
|
||||
}
|
||||
}
|
||||
|
||||
// Meter sets the meter option
|
||||
func Meter(m meter.Meter) Option {
|
||||
return func(o *Options) {
|
||||
o.Meter = m
|
||||
}
|
||||
}
|
||||
|
||||
// Client to use for sync/async communication
|
||||
func Client(c client.Client) Option {
|
||||
return func(o *Options) {
|
||||
o.Client = c
|
||||
}
|
||||
}
|
||||
|
||||
// Context specifies a context for the service.
|
||||
// Can be used to signal shutdown of the flow
|
||||
// or can be used for extra option values.
|
||||
func Context(ctx context.Context) Option {
|
||||
return func(o *Options) {
|
||||
o.Context = ctx
|
||||
}
|
||||
}
|
||||
|
||||
// Tracer mechanism for distributed tracking
|
||||
func Tracer(t tracer.Tracer) Option {
|
||||
return func(o *Options) {
|
||||
o.Tracer = t
|
||||
}
|
||||
}
|
||||
|
||||
// Store used for intermediate results
|
||||
func Store(s store.Store) Option {
|
||||
return func(o *Options) {
|
||||
o.Store = s
|
||||
}
|
||||
}
|
||||
|
||||
// WorflowOption func signature
|
||||
type WorkflowOption func(*WorkflowOptions)
|
||||
|
||||
// WorkflowOptions holds workflow options
|
||||
type WorkflowOptions struct {
|
||||
Context context.Context
|
||||
ID string
|
||||
}
|
||||
|
||||
// WorkflowID set workflow id
|
||||
func WorkflowID(id string) WorkflowOption {
|
||||
return func(o *WorkflowOptions) {
|
||||
o.ID = id
|
||||
}
|
||||
}
|
||||
|
||||
// ExecuteOptions holds execute options
|
||||
type ExecuteOptions struct {
|
||||
// Client holds the client.Client
|
||||
Client client.Client
|
||||
// Tracer holds the tracer
|
||||
Tracer tracer.Tracer
|
||||
// Logger holds the logger
|
||||
Logger logger.Logger
|
||||
// Meter holds the meter
|
||||
Meter meter.Meter
|
||||
// Context can be used to abort execution or pass additional opts
|
||||
Context context.Context
|
||||
// Start step
|
||||
Start string
|
||||
// Timeout for execution
|
||||
Timeout time.Duration
|
||||
// Reverse execution
|
||||
Reverse bool
|
||||
// Async enables async execution
|
||||
Async bool
|
||||
}
|
||||
|
||||
// ExecuteOption func signature
|
||||
type ExecuteOption func(*ExecuteOptions)
|
||||
|
||||
// ExecuteClient pass client.Client to ExecuteOption
|
||||
func ExecuteClient(c client.Client) ExecuteOption {
|
||||
return func(o *ExecuteOptions) {
|
||||
o.Client = c
|
||||
}
|
||||
}
|
||||
|
||||
// ExecuteTracer pass tracer.Tracer to ExecuteOption
|
||||
func ExecuteTracer(t tracer.Tracer) ExecuteOption {
|
||||
return func(o *ExecuteOptions) {
|
||||
o.Tracer = t
|
||||
}
|
||||
}
|
||||
|
||||
// ExecuteLogger pass logger.Logger to ExecuteOption
|
||||
func ExecuteLogger(l logger.Logger) ExecuteOption {
|
||||
return func(o *ExecuteOptions) {
|
||||
o.Logger = l
|
||||
}
|
||||
}
|
||||
|
||||
// ExecuteMeter pass meter.Meter to ExecuteOption
|
||||
func ExecuteMeter(m meter.Meter) ExecuteOption {
|
||||
return func(o *ExecuteOptions) {
|
||||
o.Meter = m
|
||||
}
|
||||
}
|
||||
|
||||
// ExecuteContext pass context.Context ot ExecuteOption
|
||||
func ExecuteContext(ctx context.Context) ExecuteOption {
|
||||
return func(o *ExecuteOptions) {
|
||||
o.Context = ctx
|
||||
}
|
||||
}
|
||||
|
||||
// ExecuteReverse says that dag must be run in reverse order
|
||||
func ExecuteReverse(b bool) ExecuteOption {
|
||||
return func(o *ExecuteOptions) {
|
||||
o.Reverse = b
|
||||
}
|
||||
}
|
||||
|
||||
// ExecuteTimeout pass timeout time.Duration for execution
|
||||
func ExecuteTimeout(td time.Duration) ExecuteOption {
|
||||
return func(o *ExecuteOptions) {
|
||||
o.Timeout = td
|
||||
}
|
||||
}
|
||||
|
||||
// ExecuteAsync says that caller does not wait for execution complete
|
||||
func ExecuteAsync(b bool) ExecuteOption {
|
||||
return func(o *ExecuteOptions) {
|
||||
o.Async = b
|
||||
}
|
||||
}
|
||||
|
||||
// NewExecuteOptions create new ExecuteOptions struct
|
||||
func NewExecuteOptions(opts ...ExecuteOption) ExecuteOptions {
|
||||
options := ExecuteOptions{
|
||||
Client: client.DefaultClient,
|
||||
Logger: logger.DefaultLogger,
|
||||
Tracer: tracer.DefaultTracer,
|
||||
Meter: meter.DefaultMeter,
|
||||
Context: context.Background(),
|
||||
}
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
||||
// StepOptions holds step options
|
||||
type StepOptions struct {
|
||||
Context context.Context
|
||||
Fallback string
|
||||
ID string
|
||||
Requires []string
|
||||
}
|
||||
|
||||
// StepOption func signature
|
||||
type StepOption func(*StepOptions)
|
||||
|
||||
// NewStepOptions create new StepOptions struct
|
||||
func NewStepOptions(opts ...StepOption) StepOptions {
|
||||
options := StepOptions{
|
||||
Context: context.Background(),
|
||||
}
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
||||
// StepID sets the step id for dag
|
||||
func StepID(id string) StepOption {
|
||||
return func(o *StepOptions) {
|
||||
o.ID = id
|
||||
}
|
||||
}
|
||||
|
||||
// StepRequires specifies required steps
|
||||
func StepRequires(steps ...string) StepOption {
|
||||
return func(o *StepOptions) {
|
||||
o.Requires = steps
|
||||
}
|
||||
}
|
||||
|
||||
// StepFallback set the step to run on error
|
||||
func StepFallback(step string) StepOption {
|
||||
return func(o *StepOptions) {
|
||||
o.Fallback = step
|
||||
}
|
||||
}
|
@@ -1,3 +1,4 @@
|
||||
//go:build ignore
|
||||
// +build ignore
|
||||
|
||||
package micro
|
||||
@@ -6,7 +7,7 @@ import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/unistack-org/micro/v3/server"
|
||||
"go.unistack.org/micro/v3/server"
|
||||
)
|
||||
|
||||
// Function is a one time executing Service
|
||||
@@ -64,7 +65,7 @@ func newFunction(opts ...Option) Function {
|
||||
// make context the last thing
|
||||
fopts = append(fopts, Context(ctx))
|
||||
|
||||
service := &service{opts: NewOptions(opts...)}
|
||||
service := &service{opts: NewOptions(fopts...)}
|
||||
|
||||
fn := &function{
|
||||
cancel: cancel,
|
||||
|
@@ -1,26 +1,28 @@
|
||||
//go:build ignore
|
||||
// +build ignore
|
||||
|
||||
package micro
|
||||
|
||||
/*
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
rmemory "github.com/unistack-org/micro-register-memory"
|
||||
"go.unistack.org/micro/v3/register"
|
||||
)
|
||||
|
||||
func TestFunction(t *testing.T) {
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
|
||||
r := rmemory.NewRegister()
|
||||
|
||||
r := register.NewRegister()
|
||||
ctx := context.TODO()
|
||||
// create service
|
||||
fn := NewFunction(
|
||||
Register(r),
|
||||
Name("test.function"),
|
||||
AfterStart(func() error {
|
||||
AfterStart(func(ctx context.Context) error {
|
||||
wg.Done()
|
||||
return nil
|
||||
}),
|
||||
@@ -61,3 +63,5 @@ func TestFunction(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
*/
|
||||
|
@@ -1,3 +0,0 @@
|
||||
package micro
|
||||
|
||||
//go:generate ./.github/generate.sh
|
26
go.mod
26
go.mod
@@ -1,22 +1,14 @@
|
||||
module github.com/unistack-org/micro/v3
|
||||
module go.unistack.org/micro/v3
|
||||
|
||||
go 1.14
|
||||
go 1.16
|
||||
|
||||
require (
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/dgrijalva/jwt-go v3.2.0+incompatible
|
||||
github.com/ef-ds/deque v1.0.4
|
||||
github.com/golang/protobuf v1.4.3
|
||||
github.com/google/uuid v1.1.5
|
||||
github.com/imdario/mergo v0.3.11
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/miekg/dns v1.1.35
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect
|
||||
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c
|
||||
github.com/stretchr/testify v1.7.0
|
||||
golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad // indirect
|
||||
golang.org/x/net v0.0.0-20201224014010-6772e930b67b
|
||||
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e // indirect
|
||||
google.golang.org/protobuf v1.25.0
|
||||
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f // indirect
|
||||
github.com/golang-jwt/jwt/v4 v4.2.0
|
||||
github.com/imdario/mergo v0.3.12
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible
|
||||
github.com/silas/dag v0.0.0-20210626123444-3804bac2d6d4
|
||||
go.unistack.org/micro-proto/v3 v3.1.1
|
||||
golang.org/x/net v0.0.0-20210928044308-7d9f5e0b762b
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
|
||||
)
|
||||
|
140
go.sum
140
go.sum
@@ -1,127 +1,31 @@
|
||||
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
|
||||
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
|
||||
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
|
||||
github.com/ef-ds/deque v1.0.4 h1:iFAZNmveMT9WERAkqLJ+oaABF9AcVQ5AjXem/hroniI=
|
||||
github.com/ef-ds/deque v1.0.4/go.mod h1:gXDnTC3yqvBcHbq2lcExjtAcVrOnJCbMcZXmuj8Z4tg=
|
||||
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
|
||||
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
|
||||
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
|
||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
|
||||
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
|
||||
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
|
||||
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
|
||||
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
|
||||
github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8=
|
||||
github.com/golang/protobuf v1.4.3 h1:JjCZWpVbqXDqFVmTfYWEVTMIYrL/NPdPSCHPJ0T/raM=
|
||||
github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
||||
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
|
||||
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.0 h1:/QaMHBdZ26BB3SSst0Iwl10Epc+xhTquomWX0oZEB6w=
|
||||
github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/uuid v1.1.5 h1:kxhtnfFVi+rYdOALN0B3k9UT86zVJKfBimRaciULW4I=
|
||||
github.com/google/uuid v1.1.5/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/imdario/mergo v0.3.11 h1:3tnifQM4i+fbajXKBHXWEH+KvNHqojZ778UH75j3bGA=
|
||||
github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/miekg/dns v1.1.35 h1:oTfOaDH+mZkdcgdIjH6yBajRGtIwcwcaR+rt23ZSrJs=
|
||||
github.com/miekg/dns v1.1.35/go.mod h1:KNUDUusw/aVsxyTYZM1oqvCicbwhgbNgztCETuNZ7xM=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
|
||||
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c h1:rp5dCmg/yLR3mgFuSOe4oEnDDmGLROTvMragMUXpTQw=
|
||||
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/unistack-org/micro v1.18.0 h1:EbFiII0bKV0Xcua7o6J30MFmm4/g0Hv3ECOKzsUBihU=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad h1:DN0cp81fZ3njFcrLCytUHRSUkqBjfTo4Tx9RJTWs0EY=
|
||||
golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
|
||||
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
|
||||
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
|
||||
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20201224014010-6772e930b67b h1:iFwSg7t5GZmB/Q5TjiEAsdoLDrdJRC1RiF2WhuV29Qw=
|
||||
golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e h1:vcxGaoTs7kV8m5Np9uUNQin4BrLOthgV7252N8V+FwY=
|
||||
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190924154521-2837fb4f24fe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68 h1:nxC68pudNYkKU6jWhgrqdreuFiOQWj1Fs7T3VrH4Pjw=
|
||||
github.com/golang-jwt/jwt/v4 v4.2.0 h1:besgBTC8w8HjP6NzQdxwKH9Z5oQMZ24ThTrHp3cZ8eU=
|
||||
github.com/golang-jwt/jwt/v4 v4.2.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg=
|
||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/imdario/mergo v0.3.12 h1:b6R2BslTbIEToALKP7LxUvijTsNI9TAe80pLWN2g/HU=
|
||||
github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA=
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
|
||||
github.com/silas/dag v0.0.0-20210626123444-3804bac2d6d4 h1:fOH64AB0C3ixGf9emky61STvPJL3smxJg+1Zwx1oCdg=
|
||||
github.com/silas/dag v0.0.0-20210626123444-3804bac2d6d4/go.mod h1:7RTUFBdIRC9nZ7/3RyRNH1bdqIShrDejd1YbLwgPS+I=
|
||||
go.unistack.org/micro-proto/v3 v3.1.1 h1:78qRmltwGek5kSQ9tNmDZ9TCRvZM7YDIOgzriKvabjA=
|
||||
go.unistack.org/micro-proto/v3 v3.1.1/go.mod h1:DpRhYCBXlmSJ/AAXTmntvlh7kQkYU6eFvlmYAx4BQS8=
|
||||
golang.org/x/net v0.0.0-20210928044308-7d9f5e0b762b h1:eB48h3HiRycXNy8E0Gf5e0hv7YT6Kt14L/D73G1fuwo=
|
||||
golang.org/x/net v0.0.0-20210928044308-7d9f5e0b762b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
|
||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
|
||||
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
||||
golang.org/x/tools v0.0.0-20191216052735-49a3e744a425/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
|
||||
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
||||
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
|
||||
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
|
||||
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo=
|
||||
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
|
||||
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
|
||||
google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
|
||||
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
|
||||
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
|
||||
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
|
||||
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
|
||||
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
|
||||
google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||
google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||
google.golang.org/protobuf v1.25.0 h1:Ejskq+SyPohKW+1uil0JJMtmHCgJPJ/qWTxr8qp+R4c=
|
||||
google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||
google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+RurQ=
|
||||
google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU=
|
||||
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
|
||||
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
|
@@ -11,19 +11,12 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
func init() {
|
||||
lvl, err := GetLevel(os.Getenv("MICRO_LOG_LEVEL"))
|
||||
if err != nil {
|
||||
lvl = InfoLevel
|
||||
}
|
||||
|
||||
DefaultLogger = NewLogger(WithLevel(lvl))
|
||||
}
|
||||
|
||||
type defaultLogger struct {
|
||||
enc *json.Encoder
|
||||
logFunc LogFunc
|
||||
logfFunc LogfFunc
|
||||
opts Options
|
||||
sync.RWMutex
|
||||
opts Options
|
||||
enc *json.Encoder
|
||||
}
|
||||
|
||||
// Init(opts...) should only overwrite provided options
|
||||
@@ -33,6 +26,11 @@ func (l *defaultLogger) Init(opts ...Option) error {
|
||||
o(&l.opts)
|
||||
}
|
||||
l.enc = json.NewEncoder(l.opts.Out)
|
||||
// wrap the Log func
|
||||
for i := len(l.opts.Wrappers); i > 0; i-- {
|
||||
l.logFunc = l.opts.Wrappers[i-1].Log(l.logFunc)
|
||||
l.logfFunc = l.opts.Wrappers[i-1].Logf(l.logfFunc)
|
||||
}
|
||||
l.Unlock()
|
||||
return nil
|
||||
}
|
||||
@@ -41,6 +39,28 @@ func (l *defaultLogger) String() string {
|
||||
return "micro"
|
||||
}
|
||||
|
||||
func (l *defaultLogger) Clone(opts ...Option) Logger {
|
||||
newopts := NewOptions(opts...)
|
||||
oldopts := l.opts
|
||||
for _, o := range opts {
|
||||
o(&newopts)
|
||||
o(&oldopts)
|
||||
}
|
||||
|
||||
oldopts.Wrappers = newopts.Wrappers
|
||||
l.Lock()
|
||||
cl := &defaultLogger{opts: oldopts, logFunc: l.logFunc, logfFunc: l.logfFunc}
|
||||
l.Unlock()
|
||||
|
||||
// wrap the Log func
|
||||
for i := len(newopts.Wrappers); i > 0; i-- {
|
||||
cl.logFunc = newopts.Wrappers[i-1].Log(cl.logFunc)
|
||||
cl.logfFunc = newopts.Wrappers[i-1].Logf(cl.logfFunc)
|
||||
}
|
||||
|
||||
return cl
|
||||
}
|
||||
|
||||
func (l *defaultLogger) V(level Level) bool {
|
||||
l.RLock()
|
||||
ok := l.opts.Level.Enabled(level)
|
||||
@@ -48,18 +68,28 @@ func (l *defaultLogger) V(level Level) bool {
|
||||
return ok
|
||||
}
|
||||
|
||||
func (l *defaultLogger) Fields(fields map[string]interface{}) Logger {
|
||||
func (l *defaultLogger) Level(level Level) {
|
||||
l.Lock()
|
||||
l.opts.Fields = copyFields(fields)
|
||||
l.opts.Level = level
|
||||
l.Unlock()
|
||||
return l
|
||||
}
|
||||
|
||||
func copyFields(src map[string]interface{}) map[string]interface{} {
|
||||
dst := make(map[string]interface{}, len(src))
|
||||
for k, v := range src {
|
||||
dst[k] = v
|
||||
func (l *defaultLogger) Fields(fields ...interface{}) Logger {
|
||||
nl := &defaultLogger{opts: l.opts, enc: l.enc}
|
||||
if len(fields) == 0 {
|
||||
return nl
|
||||
} else if len(fields)%2 != 0 {
|
||||
fields = fields[:len(fields)-1]
|
||||
}
|
||||
nl.logFunc = l.logFunc
|
||||
nl.logfFunc = l.logfFunc
|
||||
nl.opts.Fields = append(nl.opts.Fields, fields...)
|
||||
return nl
|
||||
}
|
||||
|
||||
func copyFields(src []interface{}) []interface{} {
|
||||
dst := make([]interface{}, len(src))
|
||||
copy(dst, src)
|
||||
return dst
|
||||
}
|
||||
|
||||
@@ -113,27 +143,27 @@ func (l *defaultLogger) Fatal(ctx context.Context, args ...interface{}) {
|
||||
}
|
||||
|
||||
func (l *defaultLogger) Infof(ctx context.Context, msg string, args ...interface{}) {
|
||||
l.Logf(ctx, InfoLevel, msg, args...)
|
||||
l.logfFunc(ctx, InfoLevel, msg, args...)
|
||||
}
|
||||
|
||||
func (l *defaultLogger) Errorf(ctx context.Context, msg string, args ...interface{}) {
|
||||
l.Logf(ctx, ErrorLevel, msg, args...)
|
||||
l.logfFunc(ctx, ErrorLevel, msg, args...)
|
||||
}
|
||||
|
||||
func (l *defaultLogger) Debugf(ctx context.Context, msg string, args ...interface{}) {
|
||||
l.Logf(ctx, DebugLevel, msg, args...)
|
||||
l.logfFunc(ctx, DebugLevel, msg, args...)
|
||||
}
|
||||
|
||||
func (l *defaultLogger) Warnf(ctx context.Context, msg string, args ...interface{}) {
|
||||
l.Logf(ctx, WarnLevel, msg, args...)
|
||||
l.logfFunc(ctx, WarnLevel, msg, args...)
|
||||
}
|
||||
|
||||
func (l *defaultLogger) Tracef(ctx context.Context, msg string, args ...interface{}) {
|
||||
l.Logf(ctx, TraceLevel, msg, args...)
|
||||
l.logfFunc(ctx, TraceLevel, msg, args...)
|
||||
}
|
||||
|
||||
func (l *defaultLogger) Fatalf(ctx context.Context, msg string, args ...interface{}) {
|
||||
l.Logf(ctx, FatalLevel, msg, args...)
|
||||
l.logfFunc(ctx, FatalLevel, msg, args...)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
@@ -146,17 +176,23 @@ func (l *defaultLogger) Log(ctx context.Context, level Level, args ...interface{
|
||||
fields := copyFields(l.opts.Fields)
|
||||
l.RUnlock()
|
||||
|
||||
fields["level"] = level.String()
|
||||
fields = append(fields, "level", level.String())
|
||||
|
||||
if _, file, line, ok := runtime.Caller(l.opts.CallerSkipCount); ok {
|
||||
fields["caller"] = fmt.Sprintf("%s:%d", logCallerfilePath(file), line)
|
||||
fields = append(fields, "caller", fmt.Sprintf("%s:%d", logCallerfilePath(file), line))
|
||||
}
|
||||
fields = append(fields, "timestamp", time.Now().Format("2006-01-02 15:04:05"))
|
||||
|
||||
if len(args) > 0 {
|
||||
fields = append(fields, "msg", fmt.Sprint(args...))
|
||||
}
|
||||
|
||||
fields["timestamp"] = time.Now().Format("2006-01-02 15:04:05")
|
||||
fields["msg"] = fmt.Sprint(args...)
|
||||
|
||||
out := make(map[string]interface{}, len(fields)/2)
|
||||
for i := 0; i < len(fields); i += 2 {
|
||||
out[fields[i].(string)] = fields[i+1]
|
||||
}
|
||||
l.RLock()
|
||||
_ = l.enc.Encode(fields)
|
||||
_ = l.enc.Encode(out)
|
||||
l.RUnlock()
|
||||
}
|
||||
|
||||
@@ -169,35 +205,39 @@ func (l *defaultLogger) Logf(ctx context.Context, level Level, msg string, args
|
||||
fields := copyFields(l.opts.Fields)
|
||||
l.RUnlock()
|
||||
|
||||
fields["level"] = level.String()
|
||||
fields = append(fields, "level", level.String())
|
||||
|
||||
if _, file, line, ok := runtime.Caller(l.opts.CallerSkipCount); ok {
|
||||
fields["caller"] = fmt.Sprintf("%s:%d", logCallerfilePath(file), line)
|
||||
fields = append(fields, "caller", fmt.Sprintf("%s:%d", logCallerfilePath(file), line))
|
||||
}
|
||||
|
||||
fields["timestamp"] = time.Now().Format("2006-01-02 15:04:05")
|
||||
fields = append(fields, "timestamp", time.Now().Format("2006-01-02 15:04:05"))
|
||||
if len(args) > 0 {
|
||||
fields["msg"] = fmt.Sprintf(msg, args...)
|
||||
} else {
|
||||
fields["msg"] = msg
|
||||
fields = append(fields, "msg", fmt.Sprintf(msg, args...))
|
||||
} else if msg != "" {
|
||||
fields = append(fields, "msg", msg)
|
||||
}
|
||||
|
||||
out := make(map[string]interface{}, len(fields)/2)
|
||||
for i := 0; i < len(fields); i += 2 {
|
||||
out[fields[i].(string)] = fields[i+1]
|
||||
}
|
||||
l.RLock()
|
||||
_ = l.enc.Encode(fields)
|
||||
_ = l.enc.Encode(out)
|
||||
l.RUnlock()
|
||||
}
|
||||
|
||||
func (l *defaultLogger) Options() Options {
|
||||
// not guard against options Context values
|
||||
l.RLock()
|
||||
opts := l.opts
|
||||
opts.Fields = copyFields(l.opts.Fields)
|
||||
l.RUnlock()
|
||||
return opts
|
||||
return l.opts
|
||||
}
|
||||
|
||||
// NewLogger builds a new logger based on options
|
||||
func NewLogger(opts ...Option) Logger {
|
||||
l := &defaultLogger{opts: NewOptions(opts...)}
|
||||
l := &defaultLogger{
|
||||
opts: NewOptions(opts...),
|
||||
}
|
||||
l.logFunc = l.Log
|
||||
l.logfFunc = l.Logf
|
||||
l.enc = json.NewEncoder(l.opts.Out)
|
||||
return l
|
||||
}
|
@@ -1,24 +1,20 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// Level means logger level
|
||||
type Level int8
|
||||
|
||||
const (
|
||||
// TraceLevel level. Designates finer-grained informational events than the Debug.
|
||||
// TraceLevel level usually used to find bugs, very verbose
|
||||
TraceLevel Level = iota - 2
|
||||
// DebugLevel level. Usually only enabled when debugging. Very verbose logging.
|
||||
// DebugLevel level used only when enabled debugging
|
||||
DebugLevel
|
||||
// InfoLevel level. General operational entries about what's going on inside the application.
|
||||
// InfoLevel level used for general info about what's going on inside the application
|
||||
InfoLevel
|
||||
// WarnLevel level. Non-critical entries that deserve eyes.
|
||||
// WarnLevel level used for non-critical entries
|
||||
WarnLevel
|
||||
// ErrorLevel level. Used for errors that should definitely be noted.
|
||||
// ErrorLevel level used for errors that should definitely be noted
|
||||
ErrorLevel
|
||||
// FatalLevel level. Logs and then calls `os.Exit(1)`. highest level of severity.
|
||||
// FatalLevel level used for critical errors and then calls `os.Exit(1)`
|
||||
FatalLevel
|
||||
)
|
||||
|
||||
@@ -38,7 +34,7 @@ func (l Level) String() string {
|
||||
case FatalLevel:
|
||||
return "fatal"
|
||||
}
|
||||
return ""
|
||||
return "info"
|
||||
}
|
||||
|
||||
// Enabled returns true if the given level is at or above this level.
|
||||
@@ -46,22 +42,22 @@ func (l Level) Enabled(lvl Level) bool {
|
||||
return lvl >= l
|
||||
}
|
||||
|
||||
// GetLevel converts a level string into a logger Level value.
|
||||
// returns an error if the input string does not match known values.
|
||||
func GetLevel(levelStr string) (Level, error) {
|
||||
switch levelStr {
|
||||
// ParseLevel converts a level string into a logger Level value.
|
||||
// returns an InfoLevel if the input string does not match known values.
|
||||
func ParseLevel(lvl string) Level {
|
||||
switch lvl {
|
||||
case TraceLevel.String():
|
||||
return TraceLevel, nil
|
||||
return TraceLevel
|
||||
case DebugLevel.String():
|
||||
return DebugLevel, nil
|
||||
return DebugLevel
|
||||
case InfoLevel.String():
|
||||
return InfoLevel, nil
|
||||
return InfoLevel
|
||||
case WarnLevel.String():
|
||||
return WarnLevel, nil
|
||||
return WarnLevel
|
||||
case ErrorLevel.String():
|
||||
return ErrorLevel, nil
|
||||
return ErrorLevel
|
||||
case FatalLevel.String():
|
||||
return FatalLevel, nil
|
||||
return FatalLevel
|
||||
}
|
||||
return InfoLevel, fmt.Errorf("unknown Level String: '%s', use InfoLevel", levelStr)
|
||||
return InfoLevel
|
||||
}
|
||||
|
@@ -1,25 +1,34 @@
|
||||
// Package logger provides a log interface
|
||||
package logger
|
||||
package logger // import "go.unistack.org/micro/v3/logger"
|
||||
|
||||
import "context"
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
)
|
||||
|
||||
var (
|
||||
// DefaultLogger variable
|
||||
DefaultLogger Logger = NewLogger()
|
||||
// DefaultLogger level
|
||||
DefaultLogger Logger = NewLogger(WithLevel(ParseLevel(os.Getenv("MICRO_LOG_LEVEL"))))
|
||||
// DefaultLevel used by logger
|
||||
DefaultLevel Level = InfoLevel
|
||||
// DefaultCallerSkipCount used by logger
|
||||
DefaultCallerSkipCount = 2
|
||||
)
|
||||
|
||||
// Logger is a generic logging interface
|
||||
type Logger interface {
|
||||
// Init initialises options
|
||||
Init(opts ...Option) error
|
||||
// Clone create logger copy with new options
|
||||
Clone(opts ...Option) Logger
|
||||
// V compare provided verbosity level with current log level
|
||||
V(level Level) bool
|
||||
// Level sets the log level for logger
|
||||
Level(level Level)
|
||||
// The Logger options
|
||||
Options() Options
|
||||
// Fields set fields to always be logged
|
||||
Fields(fields map[string]interface{}) Logger
|
||||
// Fields set fields to always be logged with keyval pairs
|
||||
Fields(fields ...interface{}) Logger
|
||||
// Info level message
|
||||
Info(ctx context.Context, args ...interface{})
|
||||
// Trace level message
|
||||
@@ -52,6 +61,9 @@ type Logger interface {
|
||||
String() string
|
||||
}
|
||||
|
||||
// Field contains keyval pair
|
||||
type Field interface{}
|
||||
|
||||
// Info writes msg to default logger on info level
|
||||
func Info(ctx context.Context, args ...interface{}) {
|
||||
DefaultLogger.Info(ctx, args...)
|
||||
@@ -123,6 +135,6 @@ func Init(opts ...Option) error {
|
||||
}
|
||||
|
||||
// Fields create logger with specific fields
|
||||
func Fields(fields map[string]interface{}) Logger {
|
||||
return DefaultLogger.Fields(fields)
|
||||
func Fields(fields ...interface{}) Logger {
|
||||
return DefaultLogger.Fields(fields...)
|
||||
}
|
||||
|
@@ -1,18 +1,148 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"log"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestContext(t *testing.T) {
|
||||
ctx := context.TODO()
|
||||
buf := bytes.NewBuffer(nil)
|
||||
l := NewLogger(WithLevel(TraceLevel), WithOutput(buf))
|
||||
if err := l.Init(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
nl, ok := FromContext(NewContext(ctx, l.Fields("key", "val")))
|
||||
if !ok {
|
||||
t.Fatal("context without logger")
|
||||
}
|
||||
nl.Info(ctx, "message")
|
||||
if !bytes.Contains(buf.Bytes(), []byte(`"key":"val"`)) {
|
||||
t.Fatalf("logger fields not works, buf contains: %s", buf.Bytes())
|
||||
}
|
||||
}
|
||||
|
||||
func TestFields(t *testing.T) {
|
||||
ctx := context.TODO()
|
||||
buf := bytes.NewBuffer(nil)
|
||||
l := NewLogger(WithLevel(TraceLevel), WithOutput(buf))
|
||||
if err := l.Init(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l.Fields("key", "val").Info(ctx, "message")
|
||||
if !bytes.Contains(buf.Bytes(), []byte(`"key":"val"`)) {
|
||||
t.Fatalf("logger fields not works, buf contains: %s", buf.Bytes())
|
||||
}
|
||||
}
|
||||
|
||||
func TestClone(t *testing.T) {
|
||||
ctx := context.TODO()
|
||||
buf := bytes.NewBuffer(nil)
|
||||
l := NewLogger(WithLevel(TraceLevel), WithOutput(buf))
|
||||
if err := l.Init(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nl := l.Clone(WithLevel(ErrorLevel))
|
||||
if err := nl.Init(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nl.Info(ctx, "info message")
|
||||
if len(buf.Bytes()) != 0 {
|
||||
t.Fatal("message must not be logged")
|
||||
}
|
||||
l.Info(ctx, "info message")
|
||||
if len(buf.Bytes()) == 0 {
|
||||
t.Fatal("message must be logged")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedirectStdLogger(t *testing.T) {
|
||||
buf := bytes.NewBuffer(nil)
|
||||
l := NewLogger(WithLevel(TraceLevel), WithOutput(buf))
|
||||
if err := l.Init(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fn := RedirectStdLogger(l, ErrorLevel)
|
||||
defer fn()
|
||||
log.Print("test")
|
||||
if !bytes.Contains(buf.Bytes(), []byte(`"level":"error","msg":"test","timestamp"`)) {
|
||||
t.Fatalf("logger error, buf %s", buf.Bytes())
|
||||
}
|
||||
}
|
||||
|
||||
func TestStdLogger(t *testing.T) {
|
||||
buf := bytes.NewBuffer(nil)
|
||||
l := NewLogger(WithLevel(TraceLevel), WithOutput(buf))
|
||||
if err := l.Init(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lg := NewStdLogger(l, ErrorLevel)
|
||||
lg.Print("test")
|
||||
if !bytes.Contains(buf.Bytes(), []byte(`"level":"error","msg":"test","timestamp"`)) {
|
||||
t.Fatalf("logger error, buf %s", buf.Bytes())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogger(t *testing.T) {
|
||||
ctx := context.TODO()
|
||||
l := NewLogger(WithLevel(TraceLevel))
|
||||
buf := bytes.NewBuffer(nil)
|
||||
l := NewLogger(WithLevel(TraceLevel), WithOutput(buf))
|
||||
if err := l.Init(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l.Trace(ctx, "trace_msg1")
|
||||
l.Warn(ctx, "warn_msg1")
|
||||
l.Fields(map[string]interface{}{"error": "test"}).Info(ctx, "error message")
|
||||
l.Fields("error", "test").Info(ctx, "error message")
|
||||
l.Warn(ctx, "first", " ", "second")
|
||||
if !bytes.Contains(buf.Bytes(), []byte(`"level":"trace","msg":"trace_msg1"`)) {
|
||||
t.Fatalf("logger error, buf %s", buf.Bytes())
|
||||
}
|
||||
if !bytes.Contains(buf.Bytes(), []byte(`"warn","msg":"warn_msg1"`)) {
|
||||
t.Fatalf("logger error, buf %s", buf.Bytes())
|
||||
}
|
||||
if !bytes.Contains(buf.Bytes(), []byte(`"error":"test","level":"info","msg":"error message"`)) {
|
||||
t.Fatalf("logger error, buf %s", buf.Bytes())
|
||||
}
|
||||
if !bytes.Contains(buf.Bytes(), []byte(`"level":"warn","msg":"first second"`)) {
|
||||
t.Fatalf("logger error, buf %s", buf.Bytes())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoggerWrapper(t *testing.T) {
|
||||
ctx := context.TODO()
|
||||
buf := bytes.NewBuffer(nil)
|
||||
l := NewLogger(WithLevel(TraceLevel), WithOutput(buf))
|
||||
if err := l.Init(WrapLogger(NewOmitWrapper())); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
type secret struct {
|
||||
Name string
|
||||
Passw string `logger:"omit"`
|
||||
}
|
||||
s := &secret{Name: "name", Passw: "secret"}
|
||||
l.Errorf(ctx, "test %#+v", s)
|
||||
if !bytes.Contains(buf.Bytes(), []byte(`logger.secret{Name:\"name\", Passw:\"\"}"`)) {
|
||||
t.Fatalf("omit not works, struct: %v, output: %s", s, buf.Bytes())
|
||||
}
|
||||
}
|
||||
|
||||
func TestOmitLoggerWrapper(t *testing.T) {
|
||||
ctx := context.TODO()
|
||||
buf := bytes.NewBuffer(nil)
|
||||
l := NewOmitLogger(NewLogger(WithLevel(TraceLevel), WithOutput(buf)))
|
||||
if err := l.Init(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
type secret struct {
|
||||
Name string
|
||||
Passw string `logger:"omit"`
|
||||
}
|
||||
s := &secret{Name: "name", Passw: "secret"}
|
||||
l.Errorf(ctx, "test %#+v", s)
|
||||
if !bytes.Contains(buf.Bytes(), []byte(`logger.secret{Name:\"name\", Passw:\"\"}"`)) {
|
||||
t.Fatalf("omit not works, struct: %v, output: %s", s, buf.Bytes())
|
||||
}
|
||||
}
|
||||
|
@@ -11,26 +11,29 @@ type Option func(*Options)
|
||||
|
||||
// Options holds logger options
|
||||
type Options struct {
|
||||
Name string
|
||||
// The logging level the logger should log at. default is `InfoLevel`
|
||||
Level Level
|
||||
// fields to always be logged
|
||||
Fields map[string]interface{}
|
||||
// It's common to set this to a file, or leave it default which is `os.Stderr`
|
||||
// Out holds the output writer
|
||||
Out io.Writer
|
||||
// Caller skip frame count for file:line info
|
||||
CallerSkipCount int
|
||||
// Alternative options
|
||||
// Context holds exernal options
|
||||
Context context.Context
|
||||
// Fields holds additional metadata
|
||||
Fields []interface{}
|
||||
// Name holds the logger name
|
||||
Name string
|
||||
// Wrappers logger wrapper that called before actual Log/Logf function
|
||||
Wrappers []Wrapper
|
||||
// The logging level the logger should log
|
||||
Level Level
|
||||
// CallerSkipCount number of frmaes to skip
|
||||
CallerSkipCount int
|
||||
}
|
||||
|
||||
// NewOptions creates new options struct
|
||||
func NewOptions(opts ...Option) Options {
|
||||
options := Options{
|
||||
Level: DefaultLevel,
|
||||
Fields: make(map[string]interface{}),
|
||||
Fields: make([]interface{}, 0, 6),
|
||||
Out: os.Stderr,
|
||||
CallerSkipCount: 0,
|
||||
CallerSkipCount: DefaultCallerSkipCount,
|
||||
Context: context.Background(),
|
||||
}
|
||||
for _, o := range opts {
|
||||
@@ -40,7 +43,7 @@ func NewOptions(opts ...Option) Options {
|
||||
}
|
||||
|
||||
// WithFields set default fields for the logger
|
||||
func WithFields(fields map[string]interface{}) Option {
|
||||
func WithFields(fields ...interface{}) Option {
|
||||
return func(o *Options) {
|
||||
o.Fields = fields
|
||||
}
|
||||
@@ -75,8 +78,15 @@ func WithContext(ctx context.Context) Option {
|
||||
}
|
||||
|
||||
// WithName sets the name
|
||||
func withName(n string) Option {
|
||||
func WithName(n string) Option {
|
||||
return func(o *Options) {
|
||||
o.Name = n
|
||||
}
|
||||
}
|
||||
|
||||
// WrapLogger adds a logger Wrapper to a list of options passed into the logger
|
||||
func WrapLogger(w Wrapper) Option {
|
||||
return func(o *Options) {
|
||||
o.Wrappers = append(o.Wrappers, w)
|
||||
}
|
||||
}
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user