Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(grpc): GRPCClients.createClient() supports multi services in one .proto file and returns void insted of T #4159

Merged
merged 5 commits into from
Nov 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions packages/grpc/src/comsumer/clients.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as assert from 'assert';
import {
Config,
Init,
Expand Down Expand Up @@ -40,23 +41,33 @@ export class GRPCClients extends Map {
}
}

async createClient<T>(options: IGRPCClientServiceOptions): Promise<T> {
async createClient<T>(options: IGRPCClientServiceOptions): Promise<void> {
const packageDefinition = await loadProto({
loaderOptions: options.loaderOptions,
protoPath: options.protoPath,
});
const allProto = loadPackageDefinition(packageDefinition);
const packageProto: any = finePackageProto(allProto, options.package);

for (const definition in packageDefinition) {
if (!packageDefinition[definition]['format']) {
const serviceName = definition.replace(`${options.package}.`, '');
const connectionService = new packageProto[serviceName](
const connectionService: T = new packageProto[serviceName](
options.url,
credentials.createInsecure(),
options.clientOptions
);

for (const methodName of Object.keys(packageDefinition[definition])) {
const originMethod = connectionService[methodName];
const msg: string[] = [
`No method found in proto file, path: ${options.protoPath}`,
`method: ${methodName}`,
`definition: ${definition}`,
`serviceName: ${serviceName}`,
];
assert(originMethod, msg.join(', '));

connectionService[methodName] = (
clientOptions: IClientOptions = {}
) => {
Expand All @@ -70,7 +81,6 @@ export class GRPCClients extends Map {
connectionService[methodName];
}
this.set(definition, connectionService);
return connectionService;
}
}
}
Expand Down Expand Up @@ -130,5 +140,12 @@ export const createGRPCConsumer = async <T>(
};

await clients.initService();
if (typeof options.service === 'string' && options.service) {
const pkg = clients.grpcConfig.services[0].package;
const name = options.service.startsWith(`${pkg}.`)
? options.service
: `${pkg}.${options.service}`;
return clients.getService(name);
}
return Array.from(clients.values())[0];
};
4 changes: 4 additions & 0 deletions packages/grpc/src/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@ export interface IGRPCClientServiceOptions extends IGRPCServiceOptions {
* Client options. Optional.
*/
clientOptions?: ClientOptions;
/**
* Service name. Optional.
*/
service?: string;
}

export interface IMidwayGRPFrameworkOptions extends IConfigurationOptions {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"name": "ali-demo"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { join } from 'path';

export const grpc = {
services: [
{
url: 'localhost:6566',
protoPath: join(__dirname, '../../../proto/helloworld.proto'),
package: 'helloworld',
clientOptions: {
'grpc.keepalive_time_ms': 5000,
}
}
]
}

export const grpcServer = {
url: 'localhost:6566',
services: [
{
protoPath: join(__dirname, '../../../proto/hero2.proto'),
package: 'hero2',
},
{
protoPath: join(__dirname, '../../../proto/helloworld.proto'),
package: 'helloworld',
}
],
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Configuration } from '@midwayjs/core';
import * as grpc from '../../../../src';
import { join } from 'path';

@Configuration({
imports: [
grpc
],
importConfigs: [
join(__dirname, './config'),
]
})
export class AutoConfiguration {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { Metadata } from '@grpc/grpc-js';
import { IClientOptions, IClientUnaryService } from '../../../../src';


export namespace hero2 {
export interface HeroService {
findOne(data: HeroById, metadata?: Metadata): Promise<Hero>;
}
export interface HeroServiceClient {
findOne(options?: IClientOptions): IClientUnaryService<HeroById, Hero>;
}
export interface HeroById {
id?: number;
}
export interface Hero {
id?: number;
name?: string;
}

export interface HeroService2 {
findOne2(data: HeroById, metadata?: Metadata): Promise<Hero>;
}
export interface HeroService2Client {
findOne2(options?: IClientOptions): IClientUnaryService<HeroById, Hero>;
}
}

export namespace helloworld {
export interface Greeter {
sayHello (request: HelloRequest): Promise<HelloReply>
}

export interface GreeterClient {
sayHello (options?: IClientOptions): IClientUnaryService<HelloRequest, HelloReply>
}

export interface HelloRequest {
name: string;
}

export interface HelloReply {
message: string;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { MSProviderType, Provider, Provide, GrpcMethod } from '@midwayjs/core';
import { helloworld } from '../interface';

/**
* package helloworld
* service Greeter
*/
@Provide()
@Provider(MSProviderType.GRPC, { package: 'helloworld' })
export class Greeter implements helloworld.Greeter {

/**
* Implements the SayHello RPC method.
*/
@GrpcMethod()
async sayHello(request: helloworld.HelloRequest) {
return { message: 'Hello ' + request.name }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { GrpcMethod, MSProviderType, Provider, Provide, Inject, Init } from '@midwayjs/core';
import { helloworld, hero2 } from '../interface';
import { Clients } from '../../../../../src';

@Provide()
@Provider(MSProviderType.GRPC, { package: 'hero2' })
export class HeroService implements hero2.HeroService {

@Inject()
grpcClients: Clients;

greeterService: helloworld.GreeterClient;

@Init()
async init() {
this.greeterService = this.grpcClients.getService<helloworld.GreeterClient>('helloworld.Greeter');
}

@GrpcMethod()
async findOne(data) {
const result = await this.greeterService.sayHello().sendMessage({
name: 'harry'
});
return {
id: 1,
name: 'bbbb-' + result.message,
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { GrpcMethod, MSProviderType, Provider, Provide, Inject, Init } from '@midwayjs/core';
import { helloworld, hero2 } from '../interface';
import { Clients } from '../../../../../src';

@Provide()
@Provider(MSProviderType.GRPC, { package: 'hero2' })
export class HeroService2 implements hero2.HeroService2 {

@Inject()
grpcClients: Clients;

greeterService: helloworld.GreeterClient;

@Init()
async init() {
this.greeterService = this.grpcClients.getService<helloworld.GreeterClient>('helloworld.Greeter');
}

@GrpcMethod()
async findOne2(data) {
const result = await this.greeterService.sayHello().sendMessage({
name: 'harry'
});
return {
id: 1,
name: 'bbbb-' + result.message,
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ export namespace hero {
id?: number;
name?: string;
}

export interface HeroService2 {
findOne2(data: HeroById, metadata?: Metadata): Promise<Hero>;
}
export interface HeroService2Client {
findOne2(options?: IClientOptions): IClientUnaryService<HeroById, Hero>;
}
}

export namespace helloworld {
Expand Down
20 changes: 20 additions & 0 deletions packages/grpc/test/fixtures/proto/hero2.proto
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
syntax = "proto3";

package hero2;

service HeroService {
rpc FindOne (HeroById) returns (Hero) {}
}

service HeroService2 {
rpc FindOne2 (HeroById) returns (Hero) {}
}

message HeroById {
int32 id = 1;
}

message Hero {
int32 id = 1;
string name = 2;
}
47 changes: 40 additions & 7 deletions packages/grpc/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,22 @@ export namespace hero {
}
}

export namespace hero2 {
export interface HeroServiceClient {
findOne(options?: IClientOptions): IClientUnaryService<HeroById, Hero>;
}
export interface HeroById {
id?: number;
}
export interface Hero {
id?: number;
name?: string;
}
export interface HeroService2Client {
findOne2(options?: IClientOptions): IClientUnaryService<HeroById, Hero>;
}
}

export namespace helloworld {
export interface GreeterClient {
sayHello (options?: IClientOptions): IClientUnaryService<HelloRequest, HelloReply>
Expand Down Expand Up @@ -61,7 +77,6 @@ export namespace math {
}
}


describe('/test/index.test.ts', function () {

it('run with empty config', async () => {
Expand Down Expand Up @@ -108,18 +123,36 @@ describe('/test/index.test.ts', function () {

it('should create multiple grpc service in one server', async () => {
const app = await createServer('base-app-multiple-service');

const service = await createGRPCConsumer<hero.HeroServiceClient>({
const opts = {
package: 'hero',
protoPath: join(__dirname, 'fixtures/proto/hero.proto'),
url: 'localhost:6565'
});
}
const service = await createGRPCConsumer<hero.HeroServiceClient>({ ...opts, });
const result = await service.findOne().sendMessage({ id: 123 });
expect(result).toEqual({ id: 1, name: 'bbbb-Hello harry' })
await closeApp(app);
});

const result = await service.findOne().sendMessage({
id: 123
});
it('should create multiple grpc service in one server 2', async () => {
const app = await createServer('base-app-multiple-service-2');
const opts = {
package: 'hero2',
protoPath: join(__dirname, 'fixtures/proto/hero2.proto'),
url: 'localhost:6566'
}

const service = await createGRPCConsumer<hero2.HeroServiceClient>({ ...opts, });
const result = await service.findOne().sendMessage({ id: 123 });
expect(result).toEqual({ id: 1, name: 'bbbb-Hello harry' })

const service2 = await createGRPCConsumer<hero2.HeroService2Client>({ service: 'HeroService2', ...opts, });
const result2 = await service2.findOne2().sendMessage({ id: 123 });
expect(result2).toEqual({ id: 1, name: 'bbbb-Hello harry' })

const service3 = await createGRPCConsumer<hero2.HeroService2Client>({ ...opts, service: 'hero2.HeroService2' });
const result3 = await service3.findOne2().sendMessage({ id: 123 });
expect(result3).toEqual({ id: 1, name: 'bbbb-Hello harry' })
await closeApp(app);
});

Expand Down
Loading