-
Notifications
You must be signed in to change notification settings - Fork 9
/
wire.go
61 lines (46 loc) · 1.6 KB
/
wire.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package grpc
import (
"context"
"flag"
"fmt"
"strings"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"namespacelabs.dev/foundation/std/go/core"
"namespacelabs.dev/foundation/std/go/grpc/client"
"namespacelabs.dev/foundation/std/go/server"
)
const grpcConnMapKeyword = "grpc_conn_map"
var connMapStr = flag.String(grpcConnMapKeyword, "", "{caller_package}:{owner_package}/{owner_service}={endpoint}")
func ProvideConn(ctx context.Context, req *Backend) (*grpc.ClientConn, error) {
key := fmt.Sprintf("%s:%s/%s", core.InstantiationPathFromContext(ctx).Last(), req.PackageName, req.ServiceName)
endpoint := connMapFromArgs()[key]
if endpoint == "" {
// If there's no endpoint configured, assume we're doing a loopback.
endpoint = fmt.Sprintf("127.0.0.1:%d", server.ListenPort())
}
// XXX ServerResource wrapping is missing.
return client.Dial(ctx, endpoint, grpc.WithTransportCredentials(insecure.NewCredentials())) /// XXX mTLS etc.
}
func connMapFromArgs() map[string]string {
return parseConn(*connMapStr)
}
func parseConn(src string) map[string]string {
m := map[string]string{}
parts := strings.Split(src, ";")
for _, p := range parts {
v := strings.TrimSpace(p)
if v == "" {
continue
}
kvs := strings.SplitN(v, "=", 2)
if len(kvs) < 2 {
core.ZLog.Fatal().Msgf("expected key=value format in --%s", grpcConnMapKeyword)
}
m[kvs[0]] = kvs[1]
}
return m
}