@hodfords/nestjs-grpc-helper 12.3.1 → 12.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +194 -1
  2. package/commands/generate-sdk.command.js +8 -2
  3. package/commands/generate-sdk.command.js.map +1 -1
  4. package/constants/sdk-toolchain.const.d.ts +25 -0
  5. package/constants/sdk-toolchain.const.js +38 -0
  6. package/constants/sdk-toolchain.const.js.map +1 -0
  7. package/decorators/grpc-param.decorator.js +5 -4
  8. package/decorators/grpc-param.decorator.js.map +1 -1
  9. package/decorators/property.decorator.js +6 -3
  10. package/decorators/property.decorator.js.map +1 -1
  11. package/helpers/generate.helper.d.ts +3 -2
  12. package/helpers/generate.helper.js +56 -3
  13. package/helpers/generate.helper.js.map +1 -1
  14. package/helpers/sdk-naming.helper.d.ts +7 -0
  15. package/helpers/sdk-naming.helper.js +197 -0
  16. package/helpers/sdk-naming.helper.js.map +1 -0
  17. package/helpers/sdk-output.helper.d.ts +6 -0
  18. package/helpers/sdk-output.helper.js +84 -0
  19. package/helpers/sdk-output.helper.js.map +1 -0
  20. package/helpers/shell.helper.d.ts +4 -0
  21. package/helpers/shell.helper.js +36 -0
  22. package/helpers/shell.helper.js.map +1 -1
  23. package/package.json +3 -1
  24. package/services/generate-proto.service.d.ts +1 -1
  25. package/services/generate-proto.service.js +7 -3
  26. package/services/generate-proto.service.js.map +1 -1
  27. package/services/go-sdk-generator.service.d.ts +26 -0
  28. package/services/go-sdk-generator.service.js +223 -0
  29. package/services/go-sdk-generator.service.js.map +1 -0
  30. package/services/protoc.service.d.ts +5 -0
  31. package/services/protoc.service.js +26 -0
  32. package/services/protoc.service.js.map +1 -0
  33. package/services/rust-sdk-generator.service.d.ts +24 -0
  34. package/services/rust-sdk-generator.service.js +197 -0
  35. package/services/rust-sdk-generator.service.js.map +1 -0
  36. package/services/sdk-descriptor.service.d.ts +13 -0
  37. package/services/sdk-descriptor.service.js +171 -0
  38. package/services/sdk-descriptor.service.js.map +1 -0
  39. package/templates/go/client.hbs +163 -0
  40. package/templates/go/enums.hbs +14 -0
  41. package/templates/go/errors.hbs +55 -0
  42. package/templates/go/go-mod.hbs +8 -0
  43. package/templates/rust/cargo-toml.hbs +13 -0
  44. package/templates/rust/client.hbs +90 -0
  45. package/templates/rust/enums.hbs +61 -0
  46. package/templates/rust/error.hbs +52 -0
  47. package/templates/rust/lib.hbs +17 -0
  48. package/types/sdk-build-config.type.d.ts +15 -0
  49. package/types/sdk-build-config.type.js +1 -1
  50. package/types/sdk-build-config.type.js.map +1 -1
  51. package/types/sdk-descriptor.type.d.ts +30 -0
  52. package/types/sdk-descriptor.type.js +2 -0
  53. package/types/sdk-descriptor.type.js.map +1 -0
@@ -0,0 +1,171 @@
1
+ import { NullableGrpcClassResponseNamePrefix, RESPONSE_METADATA_KEY } from '@hodfords/nestjs-response';
2
+ import { Logger } from '@nestjs/common';
3
+ import { isFunction, isUndefined } from '@nestjs/common/utils/shared.utils.js';
4
+ import { isEmpty } from 'es-toolkit/compat';
5
+ import { GRPC_DESCRIPTION_METADATA_KEY, GRPC_METADATA_PARAMETERS_METADATA_KEY, GRPC_METHOD_METADATA_KEY, GRPC_PARAM_INDEX_METADATA_KEY, GRPC_STREAM_METADATA_KEY } from '../constants/metadata-key.const.js';
6
+ import { isEnumProperty } from '../helpers/api-property.helper.js';
7
+ import { extractProperties } from '../helpers/property.helper.js';
8
+ import { enumMemberName } from '../helpers/sdk-naming.helper.js';
9
+ import { isPrimitiveType } from '../helpers/type.helper.js';
10
+ import { microserviceStorage } from '../storages/microservice.storage.js';
11
+ const emptyMessage = 'google.protobuf.Empty';
12
+ const nativeTypes = {
13
+ String: 'string',
14
+ Boolean: 'bool',
15
+ Number: 'float'
16
+ };
17
+ export class SdkDescriptorService {
18
+ logger = new Logger(SdkDescriptorService.name);
19
+ describe() {
20
+ return {
21
+ services: microserviceStorage
22
+ .map((constructor) => this.describeService(constructor))
23
+ .filter((service) => service.methods.length > 0),
24
+ enums: this.describeEnums()
25
+ };
26
+ }
27
+ describeService(constructor) {
28
+ const methods = Object.getOwnPropertyNames(constructor.prototype)
29
+ .filter((propertyKey) => Reflect.hasMetadata(GRPC_METHOD_METADATA_KEY, constructor.prototype, propertyKey))
30
+ .map((propertyKey) => this.describeMethod(constructor, propertyKey));
31
+ return {
32
+ name: constructor.name,
33
+ description: Reflect.getMetadata(GRPC_DESCRIPTION_METADATA_KEY, constructor),
34
+ methods
35
+ };
36
+ }
37
+ describeMethod(constructor, propertyKey) {
38
+ const prototype = constructor.prototype;
39
+ const params = Reflect.getMetadata('design:paramtypes', prototype, propertyKey);
40
+ const parameterIndex = Reflect.getMetadata(GRPC_PARAM_INDEX_METADATA_KEY, prototype, propertyKey);
41
+ const response = Reflect.getMetadata(RESPONSE_METADATA_KEY, prototype[propertyKey]);
42
+ const metadataParams = Reflect.getMetadata(GRPC_METADATA_PARAMETERS_METADATA_KEY, prototype, propertyKey) || [];
43
+ return {
44
+ name: propertyKey,
45
+ description: Reflect.getMetadata(GRPC_DESCRIPTION_METADATA_KEY, prototype, propertyKey),
46
+ requestType: isUndefined(parameterIndex) ? undefined : params[parameterIndex].name,
47
+ ...this.describeResponse(response),
48
+ isStream: Boolean(Reflect.getMetadata(GRPC_STREAM_METADATA_KEY, prototype, propertyKey)),
49
+ metadataKeys: metadataParams.map((param) => param.name)
50
+ };
51
+ }
52
+ describeResponse(response) {
53
+ if (!response) {
54
+ return {
55
+ responseKind: 'empty',
56
+ responseType: undefined,
57
+ wireResponseType: emptyMessage,
58
+ isNullablePrimitive: false
59
+ };
60
+ }
61
+ const className = response.responseClass.name;
62
+ const isPrimitive = isPrimitiveType(response.responseClass);
63
+ const responseType = isPrimitive ? nativeTypes[className] : className;
64
+ if (response.isArray) {
65
+ return {
66
+ responseKind: isPrimitive ? 'nativeList' : 'list',
67
+ responseType,
68
+ wireResponseType: `Proto${className}List`,
69
+ isNullablePrimitive: false
70
+ };
71
+ }
72
+ if (isPrimitive) {
73
+ return {
74
+ responseKind: 'native',
75
+ responseType,
76
+ wireResponseType: `Native${className}Value`,
77
+ isNullablePrimitive: Boolean(response.isAllowEmpty)
78
+ };
79
+ }
80
+ if (response.isAllowEmpty) {
81
+ return {
82
+ responseKind: 'nullable',
83
+ responseType,
84
+ wireResponseType: `${NullableGrpcClassResponseNamePrefix}${className}`,
85
+ isNullablePrimitive: false
86
+ };
87
+ }
88
+ return { responseKind: 'single', responseType, wireResponseType: className, isNullablePrimitive: false };
89
+ }
90
+ describeEnums() {
91
+ const enums = new Map();
92
+ const properties = Object.values(extractProperties()).flat();
93
+ for (const { option } of properties) {
94
+ const isEnum = isEnumProperty(option) || (isFunction(option.enum) && !isEmpty(option.enumName));
95
+ if (!isEnum || enums.has(option.enumName)) {
96
+ continue;
97
+ }
98
+ const entries = this.describeEnumEntries(option.enum);
99
+ if (!entries.length) {
100
+ continue;
101
+ }
102
+ const isNumber = option.type === 'number' || entries.every((entry) => typeof entry.value === 'number');
103
+ const item = {
104
+ name: option.enumName,
105
+ valueType: isNumber ? 'number' : 'string',
106
+ entries
107
+ };
108
+ const skipReason = this.findEnumSkipReason(item, option.type === 'number');
109
+ if (skipReason) {
110
+ this.logger.warn(`Enum ${item.name} is skipped in the Rust and Go SDKs: ${skipReason}.`);
111
+ enums.set(option.enumName, undefined);
112
+ continue;
113
+ }
114
+ enums.set(option.enumName, item);
115
+ }
116
+ return Array.from(enums.values()).filter(Boolean);
117
+ }
118
+ findEnumSkipReason(item, isDeclaredNumber) {
119
+ const values = item.entries.map((entry) => entry.value);
120
+ if (isDeclaredNumber && values.some((value) => typeof value !== 'number')) {
121
+ return 'it is declared as a number but has non-numeric values';
122
+ }
123
+ if (item.valueType === 'string' && values.some((value) => typeof value !== 'string')) {
124
+ return 'it mixes string and number values';
125
+ }
126
+ if (item.valueType === 'number') {
127
+ const fraction = item.entries.find((entry) => !Number.isInteger(entry.value));
128
+ if (fraction) {
129
+ return `value ${fraction.value} of member "${fraction.key}" is not an integer`;
130
+ }
131
+ const outOfRange = item.entries.find((entry) => Number(entry.value) < -(2 ** 31) || Number(entry.value) >= 2 ** 31);
132
+ if (outOfRange) {
133
+ return `value ${outOfRange.value} of member "${outOfRange.key}" does not fit in an int32`;
134
+ }
135
+ }
136
+ return (this.findDuplicate(item, (entry) => String(entry.value), 'have the same value') ??
137
+ this.findNameProblem(item));
138
+ }
139
+ findNameProblem(item) {
140
+ const empty = item.entries.find((entry) => !enumMemberName(entry.key));
141
+ if (empty) {
142
+ return `member "${empty.key}" maps to an empty name`;
143
+ }
144
+ return this.findDuplicate(item, (entry) => enumMemberName(entry.key), 'map to the same name');
145
+ }
146
+ findDuplicate(item, keyOf, problem) {
147
+ const seen = new Map();
148
+ for (const entry of item.entries) {
149
+ const key = keyOf(entry);
150
+ if (seen.has(key)) {
151
+ return `members "${seen.get(key)}" and "${entry.key}" ${problem}`;
152
+ }
153
+ seen.set(key, entry.key);
154
+ }
155
+ return undefined;
156
+ }
157
+ describeEnumEntries(enumOption) {
158
+ const source = isFunction(enumOption) ? enumOption() : enumOption;
159
+ if (Array.isArray(source)) {
160
+ return Array.from(new Set(source)).map((value) => ({ key: String(value), value }));
161
+ }
162
+ if (!source || typeof source !== 'object') {
163
+ return [];
164
+ }
165
+ const record = source;
166
+ return Object.keys(record)
167
+ .filter((key) => isNaN(Number(key)))
168
+ .map((key) => ({ key, value: record[key] }));
169
+ }
170
+ }
171
+ //# sourceMappingURL=sdk-descriptor.service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sdk-descriptor.service.js","sourceRoot":"","sources":["../../../lib/services/sdk-descriptor.service.ts"],"names":[],"mappings":"AACA,OAAO,EACH,mCAAmC,EACnC,qBAAqB,EAExB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,sCAAsC,CAAC;AAC/E,OAAO,EA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,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;QAC7B,CAAC;QACD,OAAO,SAAS,CAAC;IACrB,CAAC;IAGO,mBAAmB,CAAC,UAAmB;QAC3C,MAAM,MAAM,GAAG,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC;QAClE,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;YACxB,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,GAAG,CAAkB,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;QACxG,CAAC;QACD,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;YACxC,OAAO,EAAE,CAAC;QACd,CAAC;QAED,MAAM,MAAM,GAAG,MAAyC,CAAC;QAEzD,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC;aACrB,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;aACnC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;IACrD,CAAC;CACJ"}
@@ -0,0 +1,163 @@
1
+ // Code generated by @hodfords/nestjs-grpc-helper. DO NOT EDIT.
2
+
3
+ package {{packageName}}
4
+
5
+ import (
6
+ "context"
7
+ "errors"
8
+ "io"
9
+ "strings"
10
+ "time"
11
+
12
+ "google.golang.org/grpc"
13
+ "google.golang.org/grpc/metadata"
14
+ "google.golang.org/protobuf/types/known/emptypb"
15
+
16
+ "{{{module}}}/pb"
17
+ )
18
+
19
+ var _ *emptypb.Empty
20
+
21
+ // Option configures a client or a single call.
22
+ type Option func(*config)
23
+
24
+ type config struct {
25
+ timeout time.Duration
26
+ md metadata.MD
27
+ }
28
+
29
+ // WithTimeout sets the deadline of unary calls. Passed to a constructor it is the default;
30
+ // passed to a call it overrides the default. Streams only use a timeout passed to the call.
31
+ func WithTimeout(timeout time.Duration) Option {
32
+ return func(c *config) {
33
+ c.timeout = timeout
34
+ }
35
+ }
36
+
37
+ // WithMetadata adds outgoing gRPC metadata. A later value for the same key replaces the earlier one,
38
+ // so metadata passed to a call overrides metadata passed to the constructor.
39
+ func WithMetadata(md metadata.MD) Option {
40
+ return func(c *config) {
41
+ merged := c.md.Copy()
42
+ for key, values := range md {
43
+ merged[strings.ToLower(key)] = append([]string(nil), values...)
44
+ }
45
+ c.md = merged
46
+ }
47
+ }
48
+
49
+ func newConfig(opts []Option) config {
50
+ var c config
51
+ for _, opt := range opts {
52
+ opt(&c)
53
+ }
54
+ return c
55
+ }
56
+
57
+ func (c config) with(opts []Option) config {
58
+ next := config{timeout: c.timeout, md: c.md.Copy()}
59
+ for _, opt := range opts {
60
+ opt(&next)
61
+ }
62
+ return next
63
+ }
64
+
65
+ func (c config) withoutTimeout() config {
66
+ return config{md: c.md.Copy()}
67
+ }
68
+
69
+ func prepare(ctx context.Context, cfg config) (context.Context, context.CancelFunc) {
70
+ if len(cfg.md) > 0 {
71
+ existing, _ := metadata.FromOutgoingContext(ctx)
72
+ merged := existing.Copy()
73
+ for key, values := range cfg.md {
74
+ merged[key] = append([]string(nil), values...)
75
+ }
76
+ ctx = metadata.NewOutgoingContext(ctx, merged)
77
+ }
78
+ if cfg.timeout > 0 {
79
+ return context.WithTimeout(ctx, cfg.timeout)
80
+ }
81
+ return context.WithCancel(ctx)
82
+ }
83
+
84
+ // Stream is a typed server stream. Recv returns io.EOF when the server has finished.
85
+ type Stream[T any] struct {
86
+ recv func() (T, error)
87
+ cancel context.CancelFunc
88
+ }
89
+
90
+ func (s *Stream[T]) Recv() (T, error) {
91
+ value, err := s.recv()
92
+ if err != nil {
93
+ s.cancel()
94
+ }
95
+ return value, err
96
+ }
97
+
98
+ // Close stops the stream before the server has finished.
99
+ func (s *Stream[T]) Close() {
100
+ s.cancel()
101
+ }
102
+
103
+ func wrapStreamError(err error) error {
104
+ if errors.Is(err, io.EOF) {
105
+ return io.EOF
106
+ }
107
+ return wrapError(err)
108
+ }
109
+ {{#each services}}
110
+
111
+ {{#each docLines}}
112
+ // {{{this}}}
113
+ {{/each}}
114
+ type {{clientName}} struct {
115
+ client pb.{{clientName}}
116
+ defaults config
117
+ }
118
+
119
+ func New{{clientName}}(conn grpc.ClientConnInterface, opts ...Option) *{{clientName}} {
120
+ client := &{{clientName}}{client: pb.New{{clientName}}(conn), defaults: newConfig(opts)}
121
+ return client
122
+ }
123
+ {{#each methods}}
124
+
125
+ {{#each docLines}}
126
+ // {{{this}}}
127
+ {{/each}}
128
+ func (c *{{../clientName}}) {{goName}}(ctx context.Context{{#if requestType}}, req {{{requestType}}}{{/if}}, opts ...Option) {{{signatureReturn}}} {
129
+ {{#if isStream}}
130
+ ctx, cancel := prepare(ctx, c.defaults.withoutTimeout().with(opts))
131
+ stream, err := c.client.{{goName}}(ctx, {{{requestArg}}})
132
+ if err != nil {
133
+ cancel()
134
+ return nil, wrapError(err)
135
+ }
136
+ recv := func() ({{{returnType}}}, error) {
137
+ res, err := stream.Recv()
138
+ if err != nil {
139
+ var zero {{{returnType}}}
140
+ return zero, wrapStreamError(err)
141
+ }
142
+ return {{{unwrapExpr}}}, nil
143
+ }
144
+ return &Stream[{{{returnType}}}]{recv: recv, cancel: cancel}, nil
145
+ {{else}}
146
+ ctx, cancel := prepare(ctx, c.defaults.with(opts))
147
+ defer cancel()
148
+ {{#if isEmpty}}
149
+ if _, err := c.client.{{goName}}(ctx, {{{requestArg}}}); err != nil {
150
+ return wrapError(err)
151
+ }
152
+ return nil
153
+ {{else}}
154
+ res, err := c.client.{{goName}}(ctx, {{{requestArg}}})
155
+ if err != nil {
156
+ return {{{zeroValue}}}, wrapError(err)
157
+ }
158
+ return {{{unwrapExpr}}}, nil
159
+ {{/if}}
160
+ {{/if}}
161
+ }
162
+ {{/each}}
163
+ {{/each}}
@@ -0,0 +1,14 @@
1
+ // Code generated by @hodfords/nestjs-grpc-helper. DO NOT EDIT.
2
+
3
+ package {{packageName}}
4
+ {{#each enums}}
5
+
6
+ // {{goName}} lists the values accepted for {{name}} fields. The field itself keeps its wire type.
7
+ type {{goName}} {{goType}}
8
+
9
+ const (
10
+ {{#each entries}}
11
+ {{constName}} {{../goName}} = {{{literal}}}
12
+ {{/each}}
13
+ )
14
+ {{/each}}
@@ -0,0 +1,55 @@
1
+ // Code generated by @hodfords/nestjs-grpc-helper. DO NOT EDIT.
2
+
3
+ package {{packageName}}
4
+
5
+ import (
6
+ "encoding/json"
7
+ "fmt"
8
+
9
+ "google.golang.org/grpc/codes"
10
+ "google.golang.org/grpc/status"
11
+ )
12
+
13
+ // Error is a business error returned by the service. The server sends it as an ABORTED status
14
+ // whose message is the JSON object {"message", "code", "errors"}.
15
+ type Error struct {
16
+ Code int
17
+ Message string
18
+ Errors json.RawMessage
19
+ status *status.Status
20
+ }
21
+
22
+ func (e *Error) Error() string {
23
+ return fmt.Sprintf("service error %d: %s", e.Code, e.Message)
24
+ }
25
+
26
+ // GRPCStatus returns the original status, so status.FromError keeps working.
27
+ func (e *Error) GRPCStatus() *status.Status {
28
+ return e.status
29
+ }
30
+
31
+ type errorPayload struct {
32
+ Message json.RawMessage `json:"message"`
33
+ Code int `json:"code"`
34
+ Errors json.RawMessage `json:"errors"`
35
+ }
36
+
37
+ func wrapError(err error) error {
38
+ st, ok := status.FromError(err)
39
+ if !ok || st.Code() != codes.Aborted {
40
+ return err
41
+ }
42
+
43
+ var payload errorPayload
44
+ if json.Unmarshal([]byte(st.Message()), &payload) != nil {
45
+ return err
46
+ }
47
+
48
+ message := string(payload.Message)
49
+ var text string
50
+ if json.Unmarshal(payload.Message, &text) == nil {
51
+ message = text
52
+ }
53
+
54
+ return &Error{Code: payload.Code, Message: message, Errors: payload.Errors, status: st}
55
+ }
@@ -0,0 +1,8 @@
1
+ module {{{module}}}
2
+
3
+ go {{goVersion}}
4
+
5
+ require (
6
+ google.golang.org/grpc {{grpcVersion}}
7
+ google.golang.org/protobuf {{protobufVersion}}
8
+ )
@@ -0,0 +1,13 @@
1
+ # Generated by @hodfords/nestjs-grpc-helper. Do not edit.
2
+ [package]
3
+ name = "{{crateName}}"
4
+ version = "{{version}}"
5
+ edition = "2021"
6
+ rust-version = "{{rustVersion}}"
7
+
8
+ [dependencies]
9
+ prost = "{{crates.prost}}"
10
+ tonic = "{{crates.tonic}}"
11
+ tokio-stream = "{{crates.tokioStream}}"
12
+ serde_json = "{{crates.serdeJson}}"
13
+ thiserror = "{{crates.thiserror}}"
@@ -0,0 +1,90 @@
1
+ // Generated by @hodfords/nestjs-grpc-helper. Do not edit.
2
+
3
+ use std::pin::Pin;
4
+ use std::time::Duration;
5
+
6
+ #[allow(unused_imports)]
7
+ use tokio_stream::{Stream, StreamExt};
8
+ use tonic::metadata::MetadataMap;
9
+ use tonic::transport::{Channel, Endpoint};
10
+
11
+ use crate::error::SdkError;
12
+ use crate::pb;
13
+
14
+ /// Typed server stream returned by streaming methods.
15
+ ///
16
+ /// A per-call timeout (`CallOptions.timeout`) bounds only the wait for the response to start (the
17
+ /// response headers), not the lifetime of the stream: once the stream is open it runs until the
18
+ /// server ends it or the stream is dropped.
19
+ pub type SdkStream<T> = Pin<Box<dyn Stream<Item = Result<T, SdkError>> + Send + 'static>>;
20
+
21
+ /// Options shared by every call of a client.
22
+ #[derive(Clone, Debug, Default)]
23
+ pub struct ClientOptions {
24
+ /// Default timeout of unary calls. Streams never use it.
25
+ pub timeout: Option<Duration>,
26
+ }
27
+
28
+ /// Options of a single call.
29
+ #[derive(Clone, Debug, Default)]
30
+ pub struct CallOptions {
31
+ pub metadata: MetadataMap,
32
+ /// Overrides the client's default timeout. For a stream this is the only timeout applied, and it
33
+ /// bounds the wait for the response to start (headers), not the lifetime of the stream.
34
+ /// An expired timeout is reported as `DEADLINE_EXCEEDED`.
35
+ pub timeout: Option<Duration>,
36
+ }
37
+
38
+ fn build_request<T>(message: T, timeout: Option<Duration>, metadata: MetadataMap) -> tonic::Request<T> {
39
+ let mut request = tonic::Request::new(message);
40
+ // Metadata first: set_timeout stores the deadline in the request metadata.
41
+ *request.metadata_mut() = metadata;
42
+ if let Some(timeout) = timeout {
43
+ request.set_timeout(timeout);
44
+ }
45
+ request
46
+ }
47
+ {{#each services}}
48
+
49
+ {{#each docLines}}
50
+ /// {{{this}}}
51
+ {{/each}}
52
+ #[derive(Clone, Debug)]
53
+ pub struct {{clientName}} {
54
+ inner: pb::{{moduleName}}::{{clientName}}<Channel>,
55
+ options: ClientOptions,
56
+ }
57
+
58
+ impl {{clientName}} {
59
+ /// Connects to `url`, for example `http://localhost:50051`.
60
+ pub async fn connect(url: impl Into<String>, options: ClientOptions) -> Result<Self, SdkError> {
61
+ let channel = Endpoint::from_shared(url.into())?.connect().await?;
62
+ Ok(Self::new(channel, options))
63
+ }
64
+
65
+ /// Wraps an existing channel.
66
+ pub fn new(channel: Channel, options: ClientOptions) -> Self {
67
+ let inner = pb::{{moduleName}}::{{clientName}}::new(channel);
68
+ Self { inner, options }
69
+ }
70
+ {{#each methods}}
71
+
72
+ {{#each docLines}}
73
+ /// {{{this}}}
74
+ {{/each}}
75
+ {{#if isStream}}
76
+ pub async fn {{{fnName}}}(&self{{#if requestType}}, request: {{{requestType}}}{{/if}}, options: CallOptions) -> Result<SdkStream<{{{returnType}}}>, SdkError> {
77
+ let request = build_request({{{requestArg}}}, options.timeout, options.metadata);
78
+ let stream = self.inner.clone().{{{fnName}}}(request).await.map_err(SdkError::from_status)?.into_inner();
79
+ Ok(Box::pin(stream.map(|chunk| chunk.map(|response| {{{unwrapExpr}}}).map_err(SdkError::from_status))))
80
+ }
81
+ {{else}}
82
+ pub async fn {{{fnName}}}(&self{{#if requestType}}, request: {{{requestType}}}{{/if}}, options: CallOptions) -> Result<{{{returnType}}}, SdkError> {
83
+ let request = build_request({{{requestArg}}}, options.timeout.or(self.options.timeout), options.metadata);
84
+ let response = self.inner.clone().{{{fnName}}}(request).await.map_err(SdkError::from_status)?.into_inner();
85
+ Ok({{{unwrapExpr}}})
86
+ }
87
+ {{/if}}
88
+ {{/each}}
89
+ }
90
+ {{/each}}
@@ -0,0 +1,61 @@
1
+ // Generated by @hodfords/nestjs-grpc-helper. Do not edit.
2
+ //
3
+ // Allowed values of enum fields. The fields themselves keep their wire type (String or i32).
4
+ {{#each enums}}
5
+
6
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
7
+ {{#if isNumber}}
8
+ #[repr(i32)]
9
+ pub enum {{rustName}} {
10
+ {{#each entries}}
11
+ {{variant}} = {{{literal}}},
12
+ {{/each}}
13
+ }
14
+
15
+ impl {{rustName}} {
16
+ pub const fn value(self) -> i32 {
17
+ self as i32
18
+ }
19
+
20
+ pub fn from_value(value: i32) -> Option<Self> {
21
+ match value {
22
+ {{#each entries}}
23
+ {{{literal}}} => Some(Self::{{variant}}),
24
+ {{/each}}
25
+ _ => None,
26
+ }
27
+ }
28
+ }
29
+ {{else}}
30
+ pub enum {{rustName}} {
31
+ {{#each entries}}
32
+ {{variant}},
33
+ {{/each}}
34
+ }
35
+
36
+ impl {{rustName}} {
37
+ pub const fn as_str(self) -> &'static str {
38
+ match self {
39
+ {{#each entries}}
40
+ Self::{{variant}} => {{{literal}}},
41
+ {{/each}}
42
+ }
43
+ }
44
+
45
+ pub fn from_value(value: &str) -> Option<Self> {
46
+ match value {
47
+ {{#each entries}}
48
+ {{{literal}}} => Some(Self::{{variant}}),
49
+ {{/each}}
50
+ _ => None,
51
+ }
52
+ }
53
+ }
54
+
55
+ impl std::fmt::Display for {{rustName}} {
56
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57
+ f.write_str(self.as_str())
58
+ }
59
+ }
60
+ {{/if}}
61
+ {{/each}}
@@ -0,0 +1,52 @@
1
+ // Generated by @hodfords/nestjs-grpc-helper. Do not edit.
2
+
3
+ /// Error returned by every SDK call.
4
+ #[derive(Debug, thiserror::Error)]
5
+ pub enum SdkError {
6
+ /// Business error. The server sends it as an ABORTED status whose message is the JSON object
7
+ /// `{ "message", "code", "errors" }`.
8
+ #[error("service error {code}: {message}")]
9
+ Service {
10
+ code: i64,
11
+ message: String,
12
+ errors: serde_json::Value,
13
+ },
14
+ /// Any other gRPC status, unchanged.
15
+ #[error(transparent)]
16
+ Status(tonic::Status),
17
+ /// Connection failure.
18
+ #[error(transparent)]
19
+ Transport(#[from] tonic::transport::Error),
20
+ }
21
+
22
+ impl SdkError {
23
+ pub fn from_status(status: tonic::Status) -> Self {
24
+ // tonic 0.12 enforces `Request::set_timeout` with a client-side timer and reports its expiry
25
+ // as CANCELLED with the message "Timeout expired". Report it as DEADLINE_EXCEEDED, like the
26
+ // server-side deadline and the Go SDK do.
27
+ if status.code() == tonic::Code::Cancelled && status.message() == "Timeout expired" {
28
+ return SdkError::Status(tonic::Status::deadline_exceeded("Timeout expired"));
29
+ }
30
+
31
+ if status.code() != tonic::Code::Aborted {
32
+ return SdkError::Status(status);
33
+ }
34
+
35
+ let payload = match serde_json::from_str::<serde_json::Value>(status.message()) {
36
+ Ok(serde_json::Value::Object(payload)) => payload,
37
+ _ => return SdkError::Status(status),
38
+ };
39
+
40
+ let message = match payload.get("message") {
41
+ Some(serde_json::Value::String(text)) => text.clone(),
42
+ Some(other) => other.to_string(),
43
+ None => String::new(),
44
+ };
45
+
46
+ SdkError::Service {
47
+ code: payload.get("code").and_then(serde_json::Value::as_i64).unwrap_or(0),
48
+ message,
49
+ errors: payload.get("errors").cloned().unwrap_or(serde_json::Value::Null),
50
+ }
51
+ }
52
+ }
@@ -0,0 +1,17 @@
1
+ //! Generated by @hodfords/nestjs-grpc-helper. Do not edit.
2
+
3
+ /// Messages and tonic stubs generated by protoc from `microservice.proto`.
4
+ #[allow(clippy::all, non_camel_case_types)]
5
+ pub mod pb {
6
+ include!("generated/{{{protoFile}}}");
7
+ {{#if includeTonicFile}}
8
+ include!("generated/{{{tonicFile}}}");
9
+ {{/if}}
10
+ }
11
+
12
+ pub mod client;
13
+ pub mod enums;
14
+ pub mod error;
15
+
16
+ pub use client::*;
17
+ pub use error::SdkError;