Node example

This commit is contained in:
Eden Kirin
2023-03-20 22:00:13 +01:00
parent a0d2d1cb7f
commit 1876158d9d
21 changed files with 556 additions and 13 deletions

View File

@ -1,6 +1,5 @@
PROTO_DIR=../protos PROTO_DIR=../protos
STUBS_DIR=./stubs STUBS_DIR=./stubs
PROTO_FILENAME=serve_hours.proto
run: run:
@source env/bin/activate && \ @source env/bin/activate && \
@ -14,5 +13,9 @@ proto:
--python_out=$(STUBS_DIR) \ --python_out=$(STUBS_DIR) \
--pyi_out=$(STUBS_DIR) \ --pyi_out=$(STUBS_DIR) \
--grpc_python_out=$(STUBS_DIR) \ --grpc_python_out=$(STUBS_DIR) \
$(PROTO_DIR)/$(PROTO_FILENAME) $(PROTO_DIR)/serve_hours.proto \
$(PROTO_DIR)/serve_minutes.proto \
$(PROTO_DIR)/serve_seconds.proto \
$(PROTO_DIR)/serve_milliseconds.proto \
$(PROTO_DIR)/serve_currenttime.proto
@sed -i -E 's/^(import\s[a-zA-Z0-9_]+_pb2)/from . \1/g' $(STUBS_DIR)/*_grpc.py @sed -i -E 's/^(import\s[a-zA-Z0-9_]+_pb2)/from . \1/g' $(STUBS_DIR)/*_grpc.py

View File

@ -1,8 +1,13 @@
import logging import logging
import grpc import grpc
from models import GetCurrentTimeResponse
from stubs import serve_hours_pb2 from stubs import serve_hours_pb2
from stubs import serve_hours_pb2_grpc from stubs import serve_hours_pb2_grpc
from stubs import serve_currenttime_pb2
from stubs import serve_currenttime_pb2_grpc
SERVE_CURRENTTIME_HOST = "localhost"
SERVE_CURRENTTIME_PORT = 50000
SERVE_HOURS_HOST = "localhost" SERVE_HOURS_HOST = "localhost"
SERVE_HOURS_PORT = 50001 SERVE_HOURS_PORT = 50001
SERVE_MINUTES_HOST = "localhost" SERVE_MINUTES_HOST = "localhost"
@ -23,10 +28,24 @@ def get_hours() -> int:
return response.hours return response.hours
def get_currenttime() -> GetCurrentTimeResponse:
with grpc.insecure_channel(
f"{SERVE_CURRENTTIME_HOST}:{SERVE_CURRENTTIME_PORT}"
) as channel:
stub = serve_currenttime_pb2_grpc.ServeCurrentTimeServiceStub(channel)
raw_response = stub.GetCurrentTime(
serve_currenttime_pb2.GetCurrentTimeRequest(timezone=TIMEZONE)
)
return GetCurrentTimeResponse.from_orm(raw_response)
def run(): def run():
hours = get_hours() hours = get_hours()
print(">>>>>>>>>>>>> Hours:", hours) print(">>>>>>>>>>>>> Hours:", hours)
currenttime = get_currenttime()
print(">>>>>>>>>>>>> CurrentTime:", currenttime)
if __name__ == "__main__": if __name__ == "__main__":
logging.basicConfig() logging.basicConfig()

12
src/funnel/models.py Normal file
View File

@ -0,0 +1,12 @@
from pydantic import BaseModel
class GetCurrentTimeResponse(BaseModel):
hours: int
minutes: int
seconds: int
milliseconds: int
formatted_time: str
class Config:
orm_mode = True

View File

@ -1,2 +1,3 @@
pydantic
grpcio grpcio
grpcio-tools grpcio-tools

View File

@ -0,0 +1,29 @@
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: serve_currenttime.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x17serve_currenttime.proto\x12\x11serve_currenttime\")\n\x15GetCurrentTimeRequest\x12\x10\n\x08timezone\x18\x01 \x01(\t\"w\n\x16GetCurrentTimeResponse\x12\r\n\x05hours\x18\x01 \x01(\r\x12\x0f\n\x07minutes\x18\x02 \x01(\r\x12\x0f\n\x07seconds\x18\x03 \x01(\r\x12\x14\n\x0cmilliseconds\x18\x04 \x01(\r\x12\x16\n\x0e\x66ormatted_time\x18\x05 \x01(\t2\x80\x01\n\x17ServeCurrentTimeService\x12\x65\n\x0eGetCurrentTime\x12(.serve_currenttime.GetCurrentTimeRequest\x1a).serve_currenttime.GetCurrentTimeResponseb\x06proto3')
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'serve_currenttime_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None
_GETCURRENTTIMEREQUEST._serialized_start=46
_GETCURRENTTIMEREQUEST._serialized_end=87
_GETCURRENTTIMERESPONSE._serialized_start=89
_GETCURRENTTIMERESPONSE._serialized_end=208
_SERVECURRENTTIMESERVICE._serialized_start=211
_SERVECURRENTTIMESERVICE._serialized_end=339
# @@protoc_insertion_point(module_scope)

View File

@ -0,0 +1,25 @@
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from typing import ClassVar as _ClassVar, Optional as _Optional
DESCRIPTOR: _descriptor.FileDescriptor
class GetCurrentTimeRequest(_message.Message):
__slots__ = ["timezone"]
TIMEZONE_FIELD_NUMBER: _ClassVar[int]
timezone: str
def __init__(self, timezone: _Optional[str] = ...) -> None: ...
class GetCurrentTimeResponse(_message.Message):
__slots__ = ["formatted_time", "hours", "milliseconds", "minutes", "seconds"]
FORMATTED_TIME_FIELD_NUMBER: _ClassVar[int]
HOURS_FIELD_NUMBER: _ClassVar[int]
MILLISECONDS_FIELD_NUMBER: _ClassVar[int]
MINUTES_FIELD_NUMBER: _ClassVar[int]
SECONDS_FIELD_NUMBER: _ClassVar[int]
formatted_time: str
hours: int
milliseconds: int
minutes: int
seconds: int
def __init__(self, hours: _Optional[int] = ..., minutes: _Optional[int] = ..., seconds: _Optional[int] = ..., milliseconds: _Optional[int] = ..., formatted_time: _Optional[str] = ...) -> None: ...

View File

@ -0,0 +1,66 @@
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from . import serve_currenttime_pb2 as serve__currenttime__pb2
class ServeCurrentTimeServiceStub(object):
"""Missing associated documentation comment in .proto file."""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.GetCurrentTime = channel.unary_unary(
'/serve_currenttime.ServeCurrentTimeService/GetCurrentTime',
request_serializer=serve__currenttime__pb2.GetCurrentTimeRequest.SerializeToString,
response_deserializer=serve__currenttime__pb2.GetCurrentTimeResponse.FromString,
)
class ServeCurrentTimeServiceServicer(object):
"""Missing associated documentation comment in .proto file."""
def GetCurrentTime(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_ServeCurrentTimeServiceServicer_to_server(servicer, server):
rpc_method_handlers = {
'GetCurrentTime': grpc.unary_unary_rpc_method_handler(
servicer.GetCurrentTime,
request_deserializer=serve__currenttime__pb2.GetCurrentTimeRequest.FromString,
response_serializer=serve__currenttime__pb2.GetCurrentTimeResponse.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'serve_currenttime.ServeCurrentTimeService', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
# This class is part of an EXPERIMENTAL API.
class ServeCurrentTimeService(object):
"""Missing associated documentation comment in .proto file."""
@staticmethod
def GetCurrentTime(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/serve_currenttime.ServeCurrentTimeService/GetCurrentTime',
serve__currenttime__pb2.GetCurrentTimeRequest.SerializeToString,
serve__currenttime__pb2.GetCurrentTimeResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)

View File

@ -13,13 +13,14 @@ _sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x11serve_hours.proto\"#\n\x0fGetHoursRequest\x12\x10\n\x08timezone\x18\x01 \x01(\t\"!\n\x10GetHoursResponse\x12\r\n\x05hours\x18\x01 \x01(\r2=\n\nServeHours\x12/\n\x08GetHours\x12\x10.GetHoursRequest\x1a\x11.GetHoursResponseb\x06proto3') DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x11serve_hours.proto\"#\n\x0fGetHoursRequest\x12\x10\n\x08timezone\x18\x01 \x01(\t\"!\n\x10GetHoursResponse\x12\r\n\x05hours\x18\x01 \x01(\r2=\n\nServeHours\x12/\n\x08GetHours\x12\x10.GetHoursRequest\x1a\x11.GetHoursResponseB(Z&example.com/project/protos/serve_hoursb\x06proto3')
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'serve_hours_pb2', globals()) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'serve_hours_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False: if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None DESCRIPTOR._options = None
DESCRIPTOR._serialized_options = b'Z&example.com/project/protos/serve_hours'
_GETHOURSREQUEST._serialized_start=21 _GETHOURSREQUEST._serialized_start=21
_GETHOURSREQUEST._serialized_end=56 _GETHOURSREQUEST._serialized_end=56
_GETHOURSRESPONSE._serialized_start=58 _GETHOURSRESPONSE._serialized_start=58

View File

@ -0,0 +1,29 @@
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: serve_milliseconds.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x18serve_milliseconds.proto\"*\n\x16GetMillisecondsRequest\x12\x10\n\x08timezone\x18\x01 \x01(\t\"/\n\x17GetMillisecondsResponse\x12\x14\n\x0cmilliseconds\x18\x01 \x01(\r2Y\n\x11ServeMilliseconds\x12\x44\n\x0fGetMilliseconds\x12\x17.GetMillisecondsRequest\x1a\x18.GetMillisecondsResponseb\x06proto3')
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'serve_milliseconds_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None
_GETMILLISECONDSREQUEST._serialized_start=28
_GETMILLISECONDSREQUEST._serialized_end=70
_GETMILLISECONDSRESPONSE._serialized_start=72
_GETMILLISECONDSRESPONSE._serialized_end=119
_SERVEMILLISECONDS._serialized_start=121
_SERVEMILLISECONDS._serialized_end=210
# @@protoc_insertion_point(module_scope)

View File

@ -0,0 +1,17 @@
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from typing import ClassVar as _ClassVar, Optional as _Optional
DESCRIPTOR: _descriptor.FileDescriptor
class GetMillisecondsRequest(_message.Message):
__slots__ = ["timezone"]
TIMEZONE_FIELD_NUMBER: _ClassVar[int]
timezone: str
def __init__(self, timezone: _Optional[str] = ...) -> None: ...
class GetMillisecondsResponse(_message.Message):
__slots__ = ["milliseconds"]
MILLISECONDS_FIELD_NUMBER: _ClassVar[int]
milliseconds: int
def __init__(self, milliseconds: _Optional[int] = ...) -> None: ...

View File

@ -0,0 +1,66 @@
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from . import serve_milliseconds_pb2 as serve__milliseconds__pb2
class ServeMillisecondsStub(object):
"""Missing associated documentation comment in .proto file."""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.GetMilliseconds = channel.unary_unary(
'/ServeMilliseconds/GetMilliseconds',
request_serializer=serve__milliseconds__pb2.GetMillisecondsRequest.SerializeToString,
response_deserializer=serve__milliseconds__pb2.GetMillisecondsResponse.FromString,
)
class ServeMillisecondsServicer(object):
"""Missing associated documentation comment in .proto file."""
def GetMilliseconds(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_ServeMillisecondsServicer_to_server(servicer, server):
rpc_method_handlers = {
'GetMilliseconds': grpc.unary_unary_rpc_method_handler(
servicer.GetMilliseconds,
request_deserializer=serve__milliseconds__pb2.GetMillisecondsRequest.FromString,
response_serializer=serve__milliseconds__pb2.GetMillisecondsResponse.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'ServeMilliseconds', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
# This class is part of an EXPERIMENTAL API.
class ServeMilliseconds(object):
"""Missing associated documentation comment in .proto file."""
@staticmethod
def GetMilliseconds(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/ServeMilliseconds/GetMilliseconds',
serve__milliseconds__pb2.GetMillisecondsRequest.SerializeToString,
serve__milliseconds__pb2.GetMillisecondsResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)

View File

@ -0,0 +1,29 @@
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: serve_minutes.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x13serve_minutes.proto\"%\n\x11GetMinutesRequest\x12\x10\n\x08timezone\x18\x01 \x01(\t\"%\n\x12GetMinutesResponse\x12\x0f\n\x07minutes\x18\x01 \x01(\r2E\n\x0cServeMinutes\x12\x35\n\nGetMinutes\x12\x12.GetMinutesRequest\x1a\x13.GetMinutesResponseb\x06proto3')
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'serve_minutes_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None
_GETMINUTESREQUEST._serialized_start=23
_GETMINUTESREQUEST._serialized_end=60
_GETMINUTESRESPONSE._serialized_start=62
_GETMINUTESRESPONSE._serialized_end=99
_SERVEMINUTES._serialized_start=101
_SERVEMINUTES._serialized_end=170
# @@protoc_insertion_point(module_scope)

View File

@ -0,0 +1,17 @@
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from typing import ClassVar as _ClassVar, Optional as _Optional
DESCRIPTOR: _descriptor.FileDescriptor
class GetMinutesRequest(_message.Message):
__slots__ = ["timezone"]
TIMEZONE_FIELD_NUMBER: _ClassVar[int]
timezone: str
def __init__(self, timezone: _Optional[str] = ...) -> None: ...
class GetMinutesResponse(_message.Message):
__slots__ = ["minutes"]
MINUTES_FIELD_NUMBER: _ClassVar[int]
minutes: int
def __init__(self, minutes: _Optional[int] = ...) -> None: ...

View File

@ -0,0 +1,66 @@
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from . import serve_minutes_pb2 as serve__minutes__pb2
class ServeMinutesStub(object):
"""Missing associated documentation comment in .proto file."""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.GetMinutes = channel.unary_unary(
'/ServeMinutes/GetMinutes',
request_serializer=serve__minutes__pb2.GetMinutesRequest.SerializeToString,
response_deserializer=serve__minutes__pb2.GetMinutesResponse.FromString,
)
class ServeMinutesServicer(object):
"""Missing associated documentation comment in .proto file."""
def GetMinutes(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_ServeMinutesServicer_to_server(servicer, server):
rpc_method_handlers = {
'GetMinutes': grpc.unary_unary_rpc_method_handler(
servicer.GetMinutes,
request_deserializer=serve__minutes__pb2.GetMinutesRequest.FromString,
response_serializer=serve__minutes__pb2.GetMinutesResponse.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'ServeMinutes', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
# This class is part of an EXPERIMENTAL API.
class ServeMinutes(object):
"""Missing associated documentation comment in .proto file."""
@staticmethod
def GetMinutes(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/ServeMinutes/GetMinutes',
serve__minutes__pb2.GetMinutesRequest.SerializeToString,
serve__minutes__pb2.GetMinutesResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)

View File

@ -0,0 +1,29 @@
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: serve_seconds.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x13serve_seconds.proto\"%\n\x11GetSecondsRequest\x12\x10\n\x08timezone\x18\x01 \x01(\t\"%\n\x12GetSecondsResponse\x12\x0f\n\x07seconds\x18\x01 \x01(\r2E\n\x0cServeSeconds\x12\x35\n\nGetSeconds\x12\x12.GetSecondsRequest\x1a\x13.GetSecondsResponseb\x06proto3')
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'serve_seconds_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None
_GETSECONDSREQUEST._serialized_start=23
_GETSECONDSREQUEST._serialized_end=60
_GETSECONDSRESPONSE._serialized_start=62
_GETSECONDSRESPONSE._serialized_end=99
_SERVESECONDS._serialized_start=101
_SERVESECONDS._serialized_end=170
# @@protoc_insertion_point(module_scope)

View File

@ -0,0 +1,17 @@
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from typing import ClassVar as _ClassVar, Optional as _Optional
DESCRIPTOR: _descriptor.FileDescriptor
class GetSecondsRequest(_message.Message):
__slots__ = ["timezone"]
TIMEZONE_FIELD_NUMBER: _ClassVar[int]
timezone: str
def __init__(self, timezone: _Optional[str] = ...) -> None: ...
class GetSecondsResponse(_message.Message):
__slots__ = ["seconds"]
SECONDS_FIELD_NUMBER: _ClassVar[int]
seconds: int
def __init__(self, seconds: _Optional[int] = ...) -> None: ...

View File

@ -0,0 +1,66 @@
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from . import serve_seconds_pb2 as serve__seconds__pb2
class ServeSecondsStub(object):
"""Missing associated documentation comment in .proto file."""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.GetSeconds = channel.unary_unary(
'/ServeSeconds/GetSeconds',
request_serializer=serve__seconds__pb2.GetSecondsRequest.SerializeToString,
response_deserializer=serve__seconds__pb2.GetSecondsResponse.FromString,
)
class ServeSecondsServicer(object):
"""Missing associated documentation comment in .proto file."""
def GetSeconds(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_ServeSecondsServicer_to_server(servicer, server):
rpc_method_handlers = {
'GetSeconds': grpc.unary_unary_rpc_method_handler(
servicer.GetSeconds,
request_deserializer=serve__seconds__pb2.GetSecondsRequest.FromString,
response_serializer=serve__seconds__pb2.GetSecondsResponse.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'ServeSeconds', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
# This class is part of an EXPERIMENTAL API.
class ServeSeconds(object):
"""Missing associated documentation comment in .proto file."""
@staticmethod
def GetSeconds(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/ServeSeconds/GetSeconds',
serve__seconds__pb2.GetSecondsRequest.SerializeToString,
serve__seconds__pb2.GetSecondsResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)

View File

@ -1,7 +1,7 @@
syntax = "proto3"; syntax = "proto3";
package serve_currenttime; package serve_currenttime;
service ServeCurrentTime { service ServeCurrentTimeService {
rpc GetCurrentTime(GetCurrentTimeRequest) returns (GetCurrentTimeResponse); rpc GetCurrentTime(GetCurrentTimeRequest) returns (GetCurrentTimeResponse);
} }

View File

@ -1,24 +1,51 @@
const messages = require("./stubs/serve_currenttime_pb");
const services = require("./stubs/serve_currenttime_grpc_pb");
const grpc = require("@grpc/grpc-js"); const grpc = require("@grpc/grpc-js");
const PROTO_PATH = "../protos/serve_currenttime.proto";
const protoLoader = require("@grpc/proto-loader");
var utc = require("dayjs/plugin/utc");
const timezone = require("dayjs/plugin/timezone");
const dayjs = require("dayjs");
dayjs.extend(utc);
dayjs.extend(timezone);
const SERVE_CURRENTTIME_HOST = "localhost"; const SERVE_CURRENTTIME_HOST = "localhost";
const SERVE_CURRENTTIME_PORT = 50000; const SERVE_CURRENTTIME_PORT = 50000;
function getCurrentTime(call, callback) { const options = {
var response = new messages.GetCurrentTimeResponse(); keepCase: true,
response.setMessage("Hello " + call.request.getName()); longs: String,
callback(null, response); enums: String,
defaults: true,
oneofs: true,
};
function getCurrentTime(request, callback) {
const timezone = request.timezone;
const now = dayjs().tz(timezone);
callback(null, {
hours: now.hour(),
minutes: now.minute(),
seconds: now.second(),
milliseconds: now.millisecond(),
formatted_time: now.format("YYYY-MM-DDTHH:mm:ss.SSS"),
});
} }
function main() { function main() {
console.log(`Starting server on ${SERVE_CURRENTTIME_HOST}:${SERVE_CURRENTTIME_PORT}`); var packageDefinition = protoLoader.loadSync(PROTO_PATH, options);
var server = new grpc.Server(); const serveCurrentTimeProto = grpc.loadPackageDefinition(packageDefinition).serve_currenttime;
server.addService(services.ServeCurrentTimeService, { getCurrentTime: getCurrentTime }); const server = new grpc.Server();
server.addService(serveCurrentTimeProto.ServeCurrentTimeService.service, {
getCurrentTime: getCurrentTime,
});
server.bindAsync( server.bindAsync(
`${SERVE_CURRENTTIME_HOST}:${SERVE_CURRENTTIME_PORT}`, `${SERVE_CURRENTTIME_HOST}:${SERVE_CURRENTTIME_PORT}`,
grpc.ServerCredentials.createInsecure(), grpc.ServerCredentials.createInsecure(),
() => { () => {
console.log(`Starting server on ${SERVE_CURRENTTIME_HOST}:${SERVE_CURRENTTIME_PORT}`);
server.start(); server.start();
} }
); );

View File

@ -11,6 +11,8 @@
"@grpc/grpc-js": "^1.8.12", "@grpc/grpc-js": "^1.8.12",
"@grpc/proto-loader": "^0.7.5", "@grpc/proto-loader": "^0.7.5",
"async": "^3.2.4", "async": "^3.2.4",
"dayjs": "^1.11.7",
"dayjs-timezone-iana-plugin": "^0.1.0",
"google-protobuf": "^3.21.2", "google-protobuf": "^3.21.2",
"grpc-tools": "^1.12.4", "grpc-tools": "^1.12.4",
"lodash": "^4.17.21", "lodash": "^4.17.21",
@ -256,6 +258,16 @@
"resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz",
"integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==" "integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ=="
}, },
"node_modules/dayjs": {
"version": "1.11.7",
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.7.tgz",
"integrity": "sha512-+Yw9U6YO5TQohxLcIkrXBeY73WP3ejHWVvx8XCk3gxvQDCTEmS48ZrSZCKciI7Bhl/uCMyxYtE9UqRILmFphkQ=="
},
"node_modules/dayjs-timezone-iana-plugin": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/dayjs-timezone-iana-plugin/-/dayjs-timezone-iana-plugin-0.1.0.tgz",
"integrity": "sha512-xc8cIZmi4oKr2nfu41I/FDWZKa8n8YaRMxSz9MrpXTNo8c6ZsjZuIoy5RPNmLXPqntFuITWI8obB7lUA+CdzGQ=="
},
"node_modules/debug": { "node_modules/debug": {
"version": "4.3.4", "version": "4.3.4",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz",
@ -1060,6 +1072,16 @@
"resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz",
"integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==" "integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ=="
}, },
"dayjs": {
"version": "1.11.7",
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.7.tgz",
"integrity": "sha512-+Yw9U6YO5TQohxLcIkrXBeY73WP3ejHWVvx8XCk3gxvQDCTEmS48ZrSZCKciI7Bhl/uCMyxYtE9UqRILmFphkQ=="
},
"dayjs-timezone-iana-plugin": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/dayjs-timezone-iana-plugin/-/dayjs-timezone-iana-plugin-0.1.0.tgz",
"integrity": "sha512-xc8cIZmi4oKr2nfu41I/FDWZKa8n8YaRMxSz9MrpXTNo8c6ZsjZuIoy5RPNmLXPqntFuITWI8obB7lUA+CdzGQ=="
},
"debug": { "debug": {
"version": "4.3.4", "version": "4.3.4",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz",

View File

@ -5,6 +5,8 @@
"@grpc/grpc-js": "^1.8.12", "@grpc/grpc-js": "^1.8.12",
"@grpc/proto-loader": "^0.7.5", "@grpc/proto-loader": "^0.7.5",
"async": "^3.2.4", "async": "^3.2.4",
"dayjs": "^1.11.7",
"dayjs-timezone-iana-plugin": "^0.1.0",
"google-protobuf": "^3.21.2", "google-protobuf": "^3.21.2",
"grpc-tools": "^1.12.4", "grpc-tools": "^1.12.4",
"lodash": "^4.17.21", "lodash": "^4.17.21",