MovieInfoHandler.h 20 KB
Newer Older
Yu Gan's avatar
Yu Gan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#ifndef MEDIA_MICROSERVICES_SRC_MOVIEINFOSERVICE_MOVIEINFOHANDLER_H_
#define MEDIA_MICROSERVICES_SRC_MOVIEINFOSERVICE_MOVIEINFOHANDLER_H_

#include <iostream>
#include <string>

#include <libmemcached/memcached.h>
#include <libmemcached/util.h>
#include <mongoc.h>
#include <bson/bson.h>
#include <nlohmann/json.hpp>

#include "../../gen-cpp/MovieInfoService.h"
#include "../logger.h"
#include "../tracing.h"
16 17
#include <xtrace/xtrace.h>
#include <xtrace/baggage.h>
Yu Gan's avatar
Yu Gan committed
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 62 63 64 65 66

namespace media_service {
using json = nlohmann::json;

class MovieInfoHandler : public MovieInfoServiceIf {
 public:
  MovieInfoHandler(
      memcached_pool_st *,
      mongoc_client_pool_t *);
  ~MovieInfoHandler() override = default;
  void ReadMovieInfo(MovieInfo& _return, int64_t req_id,
      const std::string& movie_id,
      const std::map<std::string, std::string> & carrier) override;
  void WriteMovieInfo(int64_t req_id, const std::string& movie_id, 
      const std::string& title, const std::vector<Cast> & casts,
      int64_t plot_id, const std::vector<std::string> & thumbnail_ids,
      const std::vector<std::string> & photo_ids,
      const std::vector<std::string> & video_ids,
      const std::string &avg_rating, int32_t num_rating,
      const std::map<std::string, std::string> & carrier) override;
  void UpdateRating(int64_t req_id, const std::string& movie_id,
      int32_t sum_uncommitted_rating, int32_t num_uncommitted_rating,
      const std::map<std::string, std::string> & carrier) override;


 private:
  memcached_pool_st *_memcached_client_pool;
  mongoc_client_pool_t *_mongodb_client_pool;
};

MovieInfoHandler::MovieInfoHandler(
    memcached_pool_st *memcached_client_pool,
    mongoc_client_pool_t *mongodb_client_pool) {
  _memcached_client_pool = memcached_client_pool;
  _mongodb_client_pool = mongodb_client_pool;
}

void MovieInfoHandler::WriteMovieInfo(
    int64_t req_id,
    const std::string &movie_id,
    const std::string &title,
    const std::vector<Cast> &casts,
    int64_t plot_id,
    const std::vector<std::string> &thumbnail_ids,
    const std::vector<std::string> &photo_ids,
    const std::vector<std::string> &video_ids,
    const std::string & avg_rating,
    int32_t num_rating,
    const std::map<std::string, std::string> &carrier) {
67 68 69 70 71 72 73 74 75 76 77

  std::map<std::string, std::string>::const_iterator baggage_it = carrier.find("baggage");
  if (baggage_it != carrier.end()) {
    SET_CURRENT_BAGGAGE(Baggage::deserialize(baggage_it->second));
  }

  if (!XTrace::IsTracing()) {
    XTrace::StartTrace("MovieInfoHandler");
  }
  XTRACE("MovieInfoHandler::WriteMovieInfo", {{"RequestID", std::to_string(req_id)}});

Yu Gan's avatar
Yu Gan committed
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
  // Initialize a span
  TextMapReader reader(carrier);
  std::map<std::string, std::string> writer_text_map;
  TextMapWriter writer(writer_text_map);
  auto parent_span = opentracing::Tracer::Global()->Extract(reader);
  auto span = opentracing::Tracer::Global()->StartSpan(
      "WriteMovieInfo",
      { opentracing::ChildOf(parent_span->get()) });
  opentracing::Tracer::Global()->Inject(span->context(), writer);

  bson_t *new_doc = bson_new();
  BSON_APPEND_UTF8(new_doc, "movie_id", movie_id.c_str());
  BSON_APPEND_UTF8(new_doc, "title", title.c_str());
  BSON_APPEND_INT64(new_doc, "plot_id", plot_id);
  BSON_APPEND_DOUBLE(new_doc, "avg_rating", std::stod(avg_rating));
  BSON_APPEND_INT64(new_doc, "num_rating", num_rating);
  const char *key;
  int idx = 0;
  char buf[16];
  
  bson_t cast_list;
  BSON_APPEND_ARRAY_BEGIN(new_doc, "casts", &cast_list);
  for (auto &cast : casts) {
    bson_uint32_to_string(idx, &key, buf, sizeof buf);
    bson_t cast_doc;
    BSON_APPEND_DOCUMENT_BEGIN(&cast_list, key, &cast_doc);
    BSON_APPEND_INT64(&cast_doc, "cast_id", cast.cast_id);
    BSON_APPEND_INT64(&cast_doc, "cast_info_id", cast.cast_info_id);
    BSON_APPEND_UTF8(&cast_doc, "character", cast.character.c_str());
    bson_append_document_end(&cast_list, &cast_doc);
    idx++;
  }
  bson_append_array_end(new_doc, &cast_list);
  
  idx = 0;
  bson_t thumbnail_id_list;
  BSON_APPEND_ARRAY_BEGIN(new_doc, "thumbnail_ids", &thumbnail_id_list);
  for (auto &thumbnail_id : thumbnail_ids) {
    bson_uint32_to_string(idx, &key, buf, sizeof buf);
    BSON_APPEND_UTF8(&thumbnail_id_list, key, thumbnail_id.c_str());
    idx++;
  }
  bson_append_array_end(new_doc, &thumbnail_id_list);

  idx = 0;
  bson_t photo_id_list;
  BSON_APPEND_ARRAY_BEGIN(new_doc, "photo_ids", &photo_id_list);
  for (auto &photo_id : photo_ids) {
    bson_uint32_to_string(idx, &key, buf, sizeof buf);
    BSON_APPEND_UTF8(&photo_id_list, key, photo_id.c_str());
    idx++;
  }
  bson_append_array_end(new_doc, &photo_id_list);

  idx = 0;
  bson_t video_id_list;
  BSON_APPEND_ARRAY_BEGIN(new_doc, "video_ids", &video_id_list);
  for (auto &video_id : video_ids) {
    bson_uint32_to_string(idx, &key, buf, sizeof buf);
    BSON_APPEND_UTF8(&video_id_list, key, video_id.c_str());
    idx++;
  }
  bson_append_array_end(new_doc, &video_id_list);

  mongoc_client_t *mongodb_client = mongoc_client_pool_pop(
      _mongodb_client_pool);
  if (!mongodb_client) {
    ServiceException se;
    se.errorCode = ErrorCode::SE_MONGODB_ERROR;
    se.message = "Failed to pop a client from MongoDB pool";
148
    XTRACE("Failed to pop a client from MongoDB pool");
Yu Gan's avatar
Yu Gan committed
149 150 151 152 153 154 155 156
    throw se;
  }
  auto collection = mongoc_client_get_collection(
      mongodb_client, "movie-info", "movie-info");
  if (!collection) {
    ServiceException se;
    se.errorCode = ErrorCode::SE_MONGODB_ERROR;
    se.message = "Failed to create collection movie-info from DB movie-info";
157
    XTRACE("Failed to create collection movie-info from DB movie-info");
Yu Gan's avatar
Yu Gan committed
158 159 160 161
    mongoc_client_pool_push(_mongodb_client_pool, mongodb_client);
    throw se;
  }
  bson_error_t error;
162
  XTRACE("MongoInsertMovieInfo start");
Yu Gan's avatar
Yu Gan committed
163 164 165 166 167
  auto insert_span = opentracing::Tracer::Global()->StartSpan(
      "MongoInsertMovieInfo", { opentracing::ChildOf(&span->context()) });
  bool plotinsert = mongoc_collection_insert_one (
      collection, new_doc, nullptr, nullptr, &error);
  insert_span->Finish();
168
  XTRACE("MongoInsertMovieInfo finish");
Yu Gan's avatar
Yu Gan committed
169 170 171
  if (!plotinsert) {
    LOG(error) << "Error: Failed to insert movie-info to MongoDB: "
               << error.message;
172
    XTRACE("Error: Failed to insert movie-info to MongoDB " + std::string(error.message));
Yu Gan's avatar
Yu Gan committed
173 174 175 176 177 178 179 180 181 182 183 184 185 186
    ServiceException se;
    se.errorCode = ErrorCode::SE_MONGODB_ERROR;
    se.message = error.message;
    bson_destroy(new_doc);
    mongoc_collection_destroy(collection);
    mongoc_client_pool_push(_mongodb_client_pool, mongodb_client);
    throw se;
  }

  bson_destroy(new_doc);
  mongoc_collection_destroy(collection);
  mongoc_client_pool_push(_mongodb_client_pool, mongodb_client);

  span->Finish();
187 188
  XTRACE("MovieInfoService::WriteMovieInfo complete");
  DELETE_CURRENT_BAGGAGE();
Yu Gan's avatar
Yu Gan committed
189 190 191 192 193 194 195 196
}

void MovieInfoHandler::ReadMovieInfo(
    MovieInfo &_return,
    int64_t req_id,
    const std::string &movie_id,
    const std::map<std::string, std::string> &carrier) {

197 198 199 200 201 202 203 204 205 206
  std::map<std::string, std::string>::const_iterator baggage_it = carrier.find("baggage");
  if (baggage_it != carrier.end()) {
    SET_CURRENT_BAGGAGE(Baggage::deserialize(baggage_it->second));
  }

  if (!XTrace::IsTracing()) {
    XTrace::StartTrace("MovieInfoHandler");
  }
  XTRACE("MovieInfoHandler::ReadMovieInfo", {{"RequestID", std::to_string(req_id)}});  

Yu Gan's avatar
Yu Gan committed
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
  // Initialize a span
  TextMapReader reader(carrier);
  std::map<std::string, std::string> writer_text_map;
  TextMapWriter writer(writer_text_map);
  auto parent_span = opentracing::Tracer::Global()->Extract(reader);
  auto span = opentracing::Tracer::Global()->StartSpan(
      "ReadMovieInfo",
      { opentracing::ChildOf(parent_span->get()) });
  opentracing::Tracer::Global()->Inject(span->context(), writer);
  
  memcached_return_t memcached_rc;
  memcached_st *memcached_client = memcached_pool_pop(
      _memcached_client_pool, true, &memcached_rc);
  if (!memcached_client) {
    ServiceException se;
    se.errorCode = ErrorCode::SE_MEMCACHED_ERROR;
    se.message = "Failed to pop a client from memcached pool";
224
    XTRACE("Failed to pop a client from memcached pool");
Yu Gan's avatar
Yu Gan committed
225 226 227 228 229
    throw se;
  }

  size_t movie_info_mmc_size;
  uint32_t memcached_flags;
230
  XTRACE("Memcached GetMovieInfo start");
Yu Gan's avatar
Yu Gan committed
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
  auto get_span = opentracing::Tracer::Global()->StartSpan(
      "MmcGetMovieInfo", { opentracing::ChildOf(&span->context()) });
  char *movie_info_mmc = memcached_get(
      memcached_client,
      movie_id.c_str(),
      movie_id.length(),
      &movie_info_mmc_size,
      &memcached_flags,
      &memcached_rc);
  if (!movie_info_mmc && memcached_rc != MEMCACHED_NOTFOUND) {
    ServiceException se;
    se.errorCode = ErrorCode::SE_MEMCACHED_ERROR;
    se.message = memcached_strerror(memcached_client, memcached_rc);
    memcached_pool_push(_memcached_client_pool, memcached_client);
    throw se;
  }
  memcached_pool_push(_memcached_client_pool, memcached_client);
  get_span->Finish();
249
  XTRACE("Memcached GetMovieInfo finish");
Yu Gan's avatar
Yu Gan committed
250 251 252

  if (movie_info_mmc) {
    LOG(debug) << "Get movie-info " << movie_id << " cache hit from Memcached";
253
    XTRACE("Cache hit in Memcached for movie " + movie_id);
Yu Gan's avatar
Yu Gan committed
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
    json movie_info_json = json::parse(std::string(
        movie_info_mmc, movie_info_mmc + movie_info_mmc_size));
    _return.movie_id = movie_info_json["movie_id"];
    _return.title = movie_info_json["title"];
    _return.avg_rating = movie_info_json["avg_rating"];
    _return.num_rating = movie_info_json["num_rating"];
    _return.plot_id = movie_info_json["plot_id"];
    for (auto &item : movie_info_json["photo_ids"]) {
      _return.photo_ids.emplace_back(item);
    }
    for (auto &item : movie_info_json["video_ids"]) {
      _return.video_ids.emplace_back(item);
    }
    for (auto &item : movie_info_json["thumbnail_ids"]) {
      _return.thumbnail_ids.emplace_back(item);
    }
    for (auto &item : movie_info_json["casts"]) {
      Cast new_cast;
      new_cast.cast_id = item["cast_id"];
      new_cast.cast_info_id = item["cast_info_id"];
      new_cast.character = item["character"];
      _return.casts.emplace_back(new_cast);
    }
    free(movie_info_mmc);
  } else {
    // If not cached in memcached
280
    XTRACE("Cache miss in Memcached.Checking in MongoDB");
Yu Gan's avatar
Yu Gan committed
281 282 283 284 285 286
    mongoc_client_t *mongodb_client = mongoc_client_pool_pop(
        _mongodb_client_pool);
    if (!mongodb_client) {
      ServiceException se;
      se.errorCode = ErrorCode::SE_MONGODB_ERROR;
      se.message = "Failed to pop a client from MongoDB pool";
287
      XTRACE("Failed to pop a client from MongoDB pool");
Yu Gan's avatar
Yu Gan committed
288 289 290 291 292 293 294 295 296
      throw se;
    }

    auto collection = mongoc_client_get_collection(
        mongodb_client, "movie-info", "movie-info");
    if (!collection) {
      ServiceException se;
      se.errorCode = ErrorCode::SE_MONGODB_ERROR;
      se.message = "Failed to create collection user from DB user";
297
      XTRACE("Failed to create collection user from DB user");
Yu Gan's avatar
Yu Gan committed
298 299 300 301 302
      mongoc_client_pool_push(_mongodb_client_pool, mongodb_client);
      throw se;
    }
    bson_t *query = bson_new();
    BSON_APPEND_UTF8(query, "movie_id", movie_id.c_str());
303
    XTRACE("MongoFindMovieInfo start");
Yu Gan's avatar
Yu Gan committed
304 305 306 307 308 309 310
    auto find_span = opentracing::Tracer::Global()->StartSpan(
        "MongoFindMovieInfo", { opentracing::ChildOf(&span->context()) });
    mongoc_cursor_t *cursor = mongoc_collection_find_with_opts(
        collection, query, nullptr, nullptr);
    const bson_t *doc;
    bool found = mongoc_cursor_next(cursor, &doc);
    find_span->Finish();
311
    XTRACE("MongoFindMovieInfo finish");
Yu Gan's avatar
Yu Gan committed
312 313 314 315
    if (!found) {
      bson_error_t error;
      if (mongoc_cursor_error (cursor, &error)) {
        LOG(warning) << error.message;
316
        XTRACE(error.message);
Yu Gan's avatar
Yu Gan committed
317 318 319 320 321 322 323 324 325 326
        bson_destroy(query);
        mongoc_cursor_destroy(cursor);
        mongoc_collection_destroy(collection);
        mongoc_client_pool_push(_mongodb_client_pool, mongodb_client);
        ServiceException se;
        se.errorCode = ErrorCode::SE_MONGODB_ERROR;
        se.message = error.message;
        throw se;
      } else {
        LOG(warning) << "Movie_id: " << movie_id << " doesn't exist in MongoDB";
327
        XTRACE("Movie_id: " + movie_id + " doesn't exist in MongoDB");
Yu Gan's avatar
Yu Gan committed
328 329 330 331 332 333 334 335 336 337 338
        bson_destroy(query);
        mongoc_cursor_destroy(cursor);
        mongoc_collection_destroy(collection);
        mongoc_client_pool_push(_mongodb_client_pool, mongodb_client);
        ServiceException se;
        se.errorCode = ErrorCode::SE_THRIFT_HANDLER_ERROR;
        se.message = "Movie_id: " + movie_id + " doesn't exist in MongoDB";
        throw se;
      }
    } else {
      LOG(debug) << "Movie_id: " << movie_id << " found in MongoDB";
339
      XTRACE("Movie_id: " + movie_id + " found in MongoDB");
Yu Gan's avatar
Yu Gan committed
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
      auto movie_info_json_char = bson_as_json(doc, nullptr);
      json movie_info_json = json::parse(movie_info_json_char);
      _return.movie_id = movie_info_json["movie_id"];
      _return.title = movie_info_json["title"];
      _return.avg_rating = movie_info_json["avg_rating"];
      _return.num_rating = movie_info_json["num_rating"];
      _return.plot_id = movie_info_json["plot_id"];
      for (auto &item : movie_info_json["photo_ids"]) {
        _return.photo_ids.emplace_back(item);
      }
      for (auto &item : movie_info_json["video_ids"]) {
        _return.video_ids.emplace_back(item);
      }
      for (auto &item : movie_info_json["thumbnail_ids"]) {
        _return.thumbnail_ids.emplace_back(item);
      }
      for (auto &item : movie_info_json["casts"]) {
        Cast new_cast;
        new_cast.cast_id = item["cast_id"];
        new_cast.cast_info_id = item["cast_info_id"];
        new_cast.character = item["character"];
        _return.casts.emplace_back(new_cast);
      }
      bson_destroy(query);
      mongoc_cursor_destroy(cursor);
      mongoc_collection_destroy(collection);
      mongoc_client_pool_push(_mongodb_client_pool, mongodb_client);

      // upload movie-info to memcached
369
      XTRACE("Uploading movie info to memcached");
Yu Gan's avatar
Yu Gan committed
370 371 372 373 374 375
      memcached_client = memcached_pool_pop(
          _memcached_client_pool, true, &memcached_rc);
      if (!memcached_client) {
        ServiceException se;
        se.errorCode = ErrorCode::SE_MEMCACHED_ERROR;
        se.message = "Failed to pop a client from memcached pool";
376
        XTRACE("Failed to pop a client from memcached pool");
Yu Gan's avatar
Yu Gan committed
377 378
        throw se;
      }
379
      XTRACE("Memcached SetMovieInfo start");
Yu Gan's avatar
Yu Gan committed
380 381 382 383 384 385 386 387 388 389 390 391 392 393
      auto set_span = opentracing::Tracer::Global()->StartSpan(
          "MmcSetMovieInfo", { opentracing::ChildOf(&span->context()) });

      memcached_rc = memcached_set(
          memcached_client,
          movie_id.c_str(),
          movie_id.length(),
          movie_info_json_char,
          std::strlen(movie_info_json_char),
          static_cast<time_t>(0),
          static_cast<uint32_t>(0));
      if (memcached_rc != MEMCACHED_SUCCESS) {
        LOG(warning) << "Failed to set movie_info to Memcached: "
                     << memcached_strerror(memcached_client, memcached_rc);
394
        XTRACE("Failed to set movie_info to Memcached");
Yu Gan's avatar
Yu Gan committed
395 396
      }
      set_span->Finish();
397
      XTRACE("Memcached SetMovieInfo complete");
Yu Gan's avatar
Yu Gan committed
398 399 400 401 402
      bson_free(movie_info_json_char);
      memcached_pool_push(_memcached_client_pool, memcached_client);
    }
  }
  span->Finish();
403 404
  XTRACE("MovieInfoHandler::ReadMovieInfo complete");
  DELETE_CURRENT_BAGGAGE();
Yu Gan's avatar
Yu Gan committed
405 406 407 408 409 410
}

void MovieInfoHandler::UpdateRating(
    int64_t req_id, const std::string& movie_id,
    int32_t sum_uncommitted_rating, int32_t num_uncommitted_rating,
    const std::map<std::string, std::string> & carrier) {
411 412 413 414 415 416 417 418 419 420 421

  std::map<std::string, std::string>::const_iterator baggage_it = carrier.find("baggage");
  if (baggage_it != carrier.end()) {
    SET_CURRENT_BAGGAGE(Baggage::deserialize(baggage_it->second));
  }

  if (!XTrace::IsTracing()) {
    XTrace::StartTrace("MovieInfoHandler");
  }
  XTRACE("MovieInfoHandler::UpdateRating", {{"RequestID", std::to_string(req_id)}});

Yu Gan's avatar
Yu Gan committed
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
  // Initialize a span
  TextMapReader reader(carrier);
  std::map<std::string, std::string> writer_text_map;
  TextMapWriter writer(writer_text_map);
  auto parent_span = opentracing::Tracer::Global()->Extract(reader);
  auto span = opentracing::Tracer::Global()->StartSpan(
      "UpdateRating",
      { opentracing::ChildOf(parent_span->get()) });
  opentracing::Tracer::Global()->Inject(span->context(), writer);

  bson_t *query = bson_new();
  BSON_APPEND_UTF8(query, "movie_id", movie_id.c_str());

  mongoc_client_t *mongodb_client = mongoc_client_pool_pop(
      _mongodb_client_pool);
  if (!mongodb_client) {
    ServiceException se;
    se.errorCode = ErrorCode::SE_MONGODB_ERROR;
    se.message = "Failed to pop a client from MongoDB pool";
441
    XTRACE("Failed to pop a client from MongoDB pool");
Yu Gan's avatar
Yu Gan committed
442 443 444 445 446 447 448 449
    throw se;
  }
  auto collection = mongoc_client_get_collection(
      mongodb_client, "social-graph", "social-graph");
  if (!collection) {
    ServiceException se;
    se.errorCode = ErrorCode::SE_MONGODB_ERROR;
    se.message = "Failed to create collection social_graph from MongoDB";
450
    XTRACE("Failed to create colletion social_graph from MongoDB");
Yu Gan's avatar
Yu Gan committed
451 452 453
    mongoc_client_pool_push(_mongodb_client_pool, mongodb_client);
    throw se;
  }
454
  XTRACE("MongoFindMovieInfo start");
Yu Gan's avatar
Yu Gan committed
455 456 457 458
  auto find_span = opentracing::Tracer::Global()->StartSpan(
      "MongoFindMovieInfo", {opentracing::ChildOf(&span->context())});
  mongoc_cursor_t *cursor = mongoc_collection_find_with_opts(
      collection, query, nullptr, nullptr);
459
  XTRACE("MongoFindMovieInfo finish");
Yu Gan's avatar
Yu Gan committed
460 461 462
  const bson_t *doc;
  bool found = mongoc_cursor_next(cursor, &doc);
  if (found) {
463
    XTRACE("MovieInfo found in MongoDB");
Yu Gan's avatar
Yu Gan committed
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
    bson_iter_t iter_0;
    bson_iter_t iter_1;
    bson_iter_init(&iter_0, doc);
    bson_iter_init(&iter_1, doc);
    double avg_rating;
    int32_t num_rating;
    if (bson_iter_init_find(&iter_0, doc, "avg_rating") &&
        bson_iter_init_find(&iter_1, doc, "num_rating")) {
      avg_rating = bson_iter_value(&iter_0)->value.v_double;
      num_rating = bson_iter_value(&iter_1)->value.v_int32;

      avg_rating = (avg_rating * num_rating + sum_uncommitted_rating) /
          (num_rating + num_uncommitted_rating);
      num_rating += num_uncommitted_rating;

      bson_t *update = BCON_NEW(
          "$set", "{",
          "avg_rating", BCON_DOUBLE(avg_rating),
          "num_rating", BCON_INT32(num_rating), "}");
      bson_error_t error;
      bson_t reply;
485
      XTRACE("MongoUpdateRating start");
Yu Gan's avatar
Yu Gan committed
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
      auto update_span = opentracing::Tracer::Global()->StartSpan(
          "MongoUpdateRating", {opentracing::ChildOf(&span->context())});
      bool updated = mongoc_collection_find_and_modify(
          collection,
          query,
          nullptr,
          update,
          nullptr,
          false,
          false,
          true,
          &reply,
          &error);
      if (!updated) {
        LOG(error) << "Failed to update rating for movie " << movie_id
                   << " to MongoDB: " << error.message;
502
        XTRACE("Failed to update rating for movie " + movie_id + " to MongoDB");
Yu Gan's avatar
Yu Gan committed
503 504 505 506 507 508 509 510 511 512 513
        ServiceException se;
        se.errorCode = ErrorCode::SE_MONGODB_ERROR;
        se.message = "Failed to update rating for movie " + movie_id +
            " to MongoDB: " + error.message;
        bson_destroy(&reply);
        bson_destroy(update);
        mongoc_collection_destroy(collection);
        mongoc_client_pool_push(_mongodb_client_pool, mongodb_client);
        throw se;
      }
      update_span->Finish();
514
      XTRACE("MongoUpdateRating finish");
Yu Gan's avatar
Yu Gan committed
515 516 517
    }
  }

518
  XTRACE("Memcached Delete Start");
Yu Gan's avatar
Yu Gan committed
519 520 521 522 523 524 525 526 527
  auto delete_span = opentracing::Tracer::Global()->StartSpan(
      "MmcDelete", {opentracing::ChildOf(&span->context())});
  memcached_return_t memcached_rc;
  memcached_st *memcached_client = memcached_pool_pop(
      _memcached_client_pool, true, &memcached_rc);
  if (!memcached_client) {
    ServiceException se;
    se.errorCode = ErrorCode::SE_MEMCACHED_ERROR;
    se.message = "Failed to pop a client from memcached pool";
528
    XTRACE("Failed to pop a client from memcached pool");
Yu Gan's avatar
Yu Gan committed
529 530 531 532 533
    throw se;
  }
  memcached_delete(memcached_client, movie_id.c_str(), movie_id.length(), 0);
  memcached_pool_push(_memcached_client_pool, memcached_client);
  delete_span->Finish();
534
  XTRACE("Memcached Delete finish");
Yu Gan's avatar
Yu Gan committed
535 536

  span->Finish();
537 538
  XTRACE("MovieInfoHandler::UpdateRating complete");
  DELETE_CURRENT_BAGGAGE();
Yu Gan's avatar
Yu Gan committed
539 540 541 542 543
}

} // namespace media_service

#endif //MEDIA_MICROSERVICES_SRC_MOVIEINFOSERVICE_MOVIEINFOHANDLER_H_