Skip to content

Commit

Permalink
feat: send grpc request to check post viewed
Browse files Browse the repository at this point in the history
  • Loading branch information
daothaison committed Aug 8, 2023
1 parent 586192a commit 30cf2c5
Show file tree
Hide file tree
Showing 16 changed files with 2,595 additions and 31 deletions.
8 changes: 6 additions & 2 deletions devspace.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,6 @@ dev:
sync:
- path: ./src/web-app:/src
startContainer: true
excludePaths:
- node_modules/
uploadExcludePaths:
- node_modules/
workingDir: /src
Expand All @@ -78,6 +76,10 @@ dev:
sync:
- path: ./src/contents-view-subgraph:/src
startContainer: true
excludePaths:
- dist/
uploadExcludePaths:
- node_modules/
workingDir: /src
command: [ "./devspace_start.sh" ]

Expand All @@ -98,5 +100,7 @@ dev:
sync:
- path: ./src/views-count-subgraph:/src
startContainer: true
uploadExcludePaths:
- node_modules/
workingDir: /src
command: [ "./devspace_start.sh" ]
4 changes: 2 additions & 2 deletions k8s/base/views-count-service.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,6 @@ spec:
app: views-count-service
type: ClusterIP
ports:
- name: http
port: 80
- name: grpc
port: 50052
targetPort: 50052
6 changes: 5 additions & 1 deletion src/views-count-service/proto/views_count.proto
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ message IncrementStoryViewRequest {

message Empty {};

message StatusResponse {
bool success = 1;
}

service ViewsCount {
rpc IncrementStoryView(IncrementStoryViewRequest) returns (Empty);
rpc IncrementStoryView(IncrementStoryViewRequest) returns (StatusResponse);
}
39 changes: 31 additions & 8 deletions src/views-count-service/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
use tonic::{transport::Server, Request, Response, Status};
use redis::{Commands, RedisError};
use views_count::views_count_server::{ViewsCount, ViewsCountServer};
use views_count::{IncrementStoryViewRequest, Empty};
use error::FromRedisError;
use views_count::{IncrementStoryViewRequest, StatusResponse};
// use error::FromRedisError;
use opentelemetry::{sdk::{trace::{self, RandomIdGenerator, Sampler}, Resource}, global, KeyValue};
use tracing_subscriber::prelude::*;
use tracing_opentelemetry;
use tracing_subscriber::Registry;

mod views_count;
mod store;
Expand All @@ -21,16 +20,40 @@ impl ViewsCount for ViewsCountService {
async fn increment_story_view(
&self,
request: Request<IncrementStoryViewRequest>,
) -> Result<Response<Empty>, Status> {
) -> Result<Response<StatusResponse>, Status> {
println!("Got a request from {:?}", request.remote_addr());
let body = request.into_inner();

let mut conn = store::connect();
let a: Result<i32, RedisError> = conn.set("key", "value");

let exists: Result<bool, RedisError> = conn.exists(format!("{}/{}", body.hashid, body.fingerprint));

match exists {
Ok(exists) => {
if exists {
println!("Key '{}' exists in Redis.", format!("{}/{}", body.hashid, body.fingerprint));
return Ok(Response::new(StatusResponse{ success: false }));
} else {
println!("Key '{}' does not exist in Redis.", format!("{}/{}", body.hashid, body.fingerprint));
}
}
Err(err) => {
eprintln!("Error checking key existence: {}", err);
}
}

let a: Result<String, RedisError> = conn.set_ex(
format!("{}/{}", body.hashid, body.fingerprint),
"value",
60
);

match a {
Ok(_) => Ok(Response::new(Empty{})),
Ok(_) => {
Ok(Response::new(StatusResponse{ success: true }))
}
Err(err) => {
Err(err.to_grpc_status())
Ok(Response::new(StatusResponse{ success: false }))
}
}
}
Expand Down Expand Up @@ -61,7 +84,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.with(tracing_opentelemetry::layer().with_tracer(tracer))
.try_init()?;

let addr = "[::1]:50052".parse().unwrap();
let addr = "0.0.0.0:50052".parse().unwrap();
let svc = ViewsCountService::default();

println!("ViewsCountServer listening on {}", addr);
Expand Down
2 changes: 1 addition & 1 deletion src/views-count-service/src/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::env;
use redis::{Client, Connection};

pub fn connect() -> Connection {
let host = env::var("REDIS_HOST").unwrap_or("redis:6789".to_owned());
let host = env::var("REDIS_HOST").unwrap_or("redis:6379".to_owned());
let password = env::var("REDIS_PASSWORD").unwrap_or_default();
let redis_conn_url = format!("redis://:{}@{}", password, host);

Expand Down
10 changes: 8 additions & 2 deletions src/views-count-service/src/views_count.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ pub struct IncrementStoryViewRequest {
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Empty {}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct StatusResponse {
#[prost(bool, tag = "1")]
pub success: bool,
}
/// Generated server implementations.
pub mod views_count_server {
#![allow(unused_variables, dead_code, missing_docs, clippy::let_unit_value)]
Expand All @@ -19,7 +25,7 @@ pub mod views_count_server {
async fn increment_story_view(
&self,
request: tonic::Request<super::IncrementStoryViewRequest>,
) -> Result<tonic::Response<super::Empty>, tonic::Status>;
) -> Result<tonic::Response<super::StatusResponse>, tonic::Status>;
}
#[derive(Debug)]
pub struct ViewsCountServer<T: ViewsCount> {
Expand Down Expand Up @@ -87,7 +93,7 @@ pub mod views_count_server {
T: ViewsCount,
> tonic::server::UnaryService<super::IncrementStoryViewRequest>
for IncrementStoryViewSvc<T> {
type Response = super::Empty;
type Response = super::StatusResponse;
type Future = BoxFuture<
tonic::Response<Self::Response>,
tonic::Status,
Expand Down
10 changes: 7 additions & 3 deletions src/views-count-subgraph/package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "content-view",
"name": "views-count-subgraph",
"version": "1.0.0",
"license": "MIT",
"scripts": {
Expand All @@ -19,12 +19,16 @@
"@opentelemetry/sdk-node": "^0.41.0",
"dotenv": "^16.3.1",
"esm": "^3.2.25",
"graphql": "^16.6.0"
"graphql": "^16.6.0",
"grpc": "^1.24.3"
},
"devDependencies": {
"@types/node": "^18.15.0",
"nodemon": "^2.0.21",
"npm-run-all": "^4.1.5",
"typescript": "^4.9.5"
"typescript": "^4.9.5",
"@types/google-protobuf": "^3.7.2",
"grpc-tools": "^1.9.1",
"grpc_tools_node_protoc_ts": "^4.1.2"
}
}
18 changes: 18 additions & 0 deletions src/views-count-subgraph/proto/build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#!/bin/bash

PROTO_DIR=./proto

# Generate JavaScript code
yarn run grpc_tools_node_protoc \
--js_out=import_style=commonjs,binary:${PROTO_DIR} \
--grpc_out=${PROTO_DIR} \
--plugin=protoc-gen-grpc=./node_modules/.bin/grpc_tools_node_protoc_plugin \
-I ./proto \
proto/*.proto

# Generate TypeScript code (d.ts)
yarn run grpc_tools_node_protoc \
--plugin=protoc-gen-ts=./node_modules/.bin/protoc-gen-ts \
--ts_out=${PROTO_DIR} \
-I ./proto \
proto/*.proto
18 changes: 18 additions & 0 deletions src/views-count-subgraph/proto/views_count.proto
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
syntax = "proto3";

package views_count;

message IncrementStoryViewRequest {
string hashid = 1;
string fingerprint = 2;
}

message Empty {};

message StatusResponse {
bool success = 1;
}

service ViewsCount {
rpc IncrementStoryView(IncrementStoryViewRequest) returns (StatusResponse);
}
41 changes: 41 additions & 0 deletions src/views-count-subgraph/proto/views_count_grpc_pb.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// package: views_count
// file: views_count.proto

/* tslint:disable */
/* eslint-disable */

import * as grpc from "grpc";
import * as views_count_pb from "./views_count_pb";

interface IViewsCountService extends grpc.ServiceDefinition<grpc.UntypedServiceImplementation> {
incrementStoryView: IViewsCountService_IIncrementStoryView;
}

interface IViewsCountService_IIncrementStoryView extends grpc.MethodDefinition<views_count_pb.IncrementStoryViewRequest, views_count_pb.StatusResponse> {
path: "/views_count.ViewsCount/IncrementStoryView";
requestStream: false;
responseStream: false;
requestSerialize: grpc.serialize<views_count_pb.IncrementStoryViewRequest>;
requestDeserialize: grpc.deserialize<views_count_pb.IncrementStoryViewRequest>;
responseSerialize: grpc.serialize<views_count_pb.StatusResponse>;
responseDeserialize: grpc.deserialize<views_count_pb.StatusResponse>;
}

export const ViewsCountService: IViewsCountService;

export interface IViewsCountServer {
incrementStoryView: grpc.handleUnaryCall<views_count_pb.IncrementStoryViewRequest, views_count_pb.StatusResponse>;
}

export interface IViewsCountClient {
incrementStoryView(request: views_count_pb.IncrementStoryViewRequest, callback: (error: grpc.ServiceError | null, response: views_count_pb.StatusResponse) => void): grpc.ClientUnaryCall;
incrementStoryView(request: views_count_pb.IncrementStoryViewRequest, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: views_count_pb.StatusResponse) => void): grpc.ClientUnaryCall;
incrementStoryView(request: views_count_pb.IncrementStoryViewRequest, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: views_count_pb.StatusResponse) => void): grpc.ClientUnaryCall;
}

export class ViewsCountClient extends grpc.Client implements IViewsCountClient {
constructor(address: string, credentials: grpc.ChannelCredentials, options?: object);
public incrementStoryView(request: views_count_pb.IncrementStoryViewRequest, callback: (error: grpc.ServiceError | null, response: views_count_pb.StatusResponse) => void): grpc.ClientUnaryCall;
public incrementStoryView(request: views_count_pb.IncrementStoryViewRequest, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: views_count_pb.StatusResponse) => void): grpc.ClientUnaryCall;
public incrementStoryView(request: views_count_pb.IncrementStoryViewRequest, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: views_count_pb.StatusResponse) => void): grpc.ClientUnaryCall;
}
44 changes: 44 additions & 0 deletions src/views-count-subgraph/proto/views_count_grpc_pb.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// GENERATED CODE -- DO NOT EDIT!

'use strict';
var grpc = require('grpc');
var views_count_pb = require('./views_count_pb.js');

function serialize_views_count_IncrementStoryViewRequest(arg) {
if (!(arg instanceof views_count_pb.IncrementStoryViewRequest)) {
throw new Error('Expected argument of type views_count.IncrementStoryViewRequest');
}
return Buffer.from(arg.serializeBinary());
}

function deserialize_views_count_IncrementStoryViewRequest(buffer_arg) {
return views_count_pb.IncrementStoryViewRequest.deserializeBinary(new Uint8Array(buffer_arg));
}

function serialize_views_count_StatusResponse(arg) {
if (!(arg instanceof views_count_pb.StatusResponse)) {
throw new Error('Expected argument of type views_count.StatusResponse');
}
return Buffer.from(arg.serializeBinary());
}

function deserialize_views_count_StatusResponse(buffer_arg) {
return views_count_pb.StatusResponse.deserializeBinary(new Uint8Array(buffer_arg));
}


var ViewsCountService = exports.ViewsCountService = {
incrementStoryView: {
path: '/views_count.ViewsCount/IncrementStoryView',
requestStream: false,
responseStream: false,
requestType: views_count_pb.IncrementStoryViewRequest,
responseType: views_count_pb.StatusResponse,
requestSerialize: serialize_views_count_IncrementStoryViewRequest,
requestDeserialize: deserialize_views_count_IncrementStoryViewRequest,
responseSerialize: serialize_views_count_StatusResponse,
responseDeserialize: deserialize_views_count_StatusResponse,
},
};

exports.ViewsCountClient = grpc.makeGenericClientConstructor(ViewsCountService);
70 changes: 70 additions & 0 deletions src/views-count-subgraph/proto/views_count_pb.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// package: views_count
// file: views_count.proto

/* tslint:disable */
/* eslint-disable */

import * as jspb from "google-protobuf";

export class IncrementStoryViewRequest extends jspb.Message {
getHashid(): string;
setHashid(value: string): IncrementStoryViewRequest;

getFingerprint(): string;
setFingerprint(value: string): IncrementStoryViewRequest;


serializeBinary(): Uint8Array;
toObject(includeInstance?: boolean): IncrementStoryViewRequest.AsObject;
static toObject(includeInstance: boolean, msg: IncrementStoryViewRequest): IncrementStoryViewRequest.AsObject;
static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>};
static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>};
static serializeBinaryToWriter(message: IncrementStoryViewRequest, writer: jspb.BinaryWriter): void;
static deserializeBinary(bytes: Uint8Array): IncrementStoryViewRequest;
static deserializeBinaryFromReader(message: IncrementStoryViewRequest, reader: jspb.BinaryReader): IncrementStoryViewRequest;
}

export namespace IncrementStoryViewRequest {
export type AsObject = {
hashid: string,
fingerprint: string,
}
}

export class Empty extends jspb.Message {

serializeBinary(): Uint8Array;
toObject(includeInstance?: boolean): Empty.AsObject;
static toObject(includeInstance: boolean, msg: Empty): Empty.AsObject;
static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>};
static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>};
static serializeBinaryToWriter(message: Empty, writer: jspb.BinaryWriter): void;
static deserializeBinary(bytes: Uint8Array): Empty;
static deserializeBinaryFromReader(message: Empty, reader: jspb.BinaryReader): Empty;
}

export namespace Empty {
export type AsObject = {
}
}

export class StatusResponse extends jspb.Message {
getSuccess(): boolean;
setSuccess(value: boolean): StatusResponse;


serializeBinary(): Uint8Array;
toObject(includeInstance?: boolean): StatusResponse.AsObject;
static toObject(includeInstance: boolean, msg: StatusResponse): StatusResponse.AsObject;
static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>};
static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>};
static serializeBinaryToWriter(message: StatusResponse, writer: jspb.BinaryWriter): void;
static deserializeBinary(bytes: Uint8Array): StatusResponse;
static deserializeBinaryFromReader(message: StatusResponse, reader: jspb.BinaryReader): StatusResponse;
}

export namespace StatusResponse {
export type AsObject = {
success: boolean,
}
}
Loading

0 comments on commit 30cf2c5

Please sign in to comment.