format.h 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #pragma once
  2. #include <library/cpp/monlib/encode/format.h>
  3. #include <util/string/ascii.h>
  4. #include <util/generic/yexception.h>
  5. #include <util/generic/typetraits.h>
  6. namespace NMonitoring {
  7. namespace NPrivate {
  8. Y_HAS_MEMBER(Name, Name);
  9. Y_HAS_MEMBER(second, Second);
  10. } // namespace NPrivate
  11. template <typename TRequest>
  12. ECompression ParseCompression(const TRequest& req) {
  13. auto&& headers = req.GetHeaders();
  14. constexpr auto isPlainPair = NPrivate::THasSecond<std::decay_t<decltype(*headers.begin())>>::value;
  15. auto it = FindIf(std::begin(headers), std::end(headers),
  16. [=] (const auto& h) {
  17. if constexpr (NPrivate::THasName<std::decay_t<decltype(h)>>::value) {
  18. return AsciiCompareIgnoreCase(h.Name(), TStringBuf("accept-encoding")) == 0;
  19. } else if (isPlainPair) {
  20. return AsciiCompareIgnoreCase(h.first, TStringBuf("accept-encoding")) == 0;
  21. }
  22. });
  23. if (it == std::end(headers)) {
  24. return NMonitoring::ECompression::IDENTITY;
  25. }
  26. NMonitoring::ECompression val{};
  27. if constexpr (isPlainPair) {
  28. val = CompressionFromAcceptEncodingHeader(it->second);
  29. } else {
  30. val = CompressionFromAcceptEncodingHeader(it->Value());
  31. }
  32. return val != NMonitoring::ECompression::UNKNOWN
  33. ? val
  34. : NMonitoring::ECompression::IDENTITY;
  35. }
  36. template <typename TRequest>
  37. NMonitoring::EFormat ParseFormat(const TRequest& req) {
  38. auto&& formatStr = req.GetParams()
  39. .Get(TStringBuf("format"));
  40. if (!formatStr.empty()) {
  41. if (formatStr == TStringBuf("SPACK")) {
  42. return EFormat::SPACK;
  43. } else if (formatStr == TStringBuf("TEXT")) {
  44. return EFormat::TEXT;
  45. } else if (formatStr == TStringBuf("JSON")) {
  46. return EFormat::JSON;
  47. } else {
  48. ythrow yexception() << "unknown format: " << formatStr << ". Only spack is supported here";
  49. }
  50. }
  51. auto&& headers = req.GetHeaders();
  52. constexpr auto isPlainPair = NPrivate::THasSecond<std::decay_t<decltype(*headers.begin())>>::value;
  53. auto it = FindIf(std::begin(headers), std::end(headers),
  54. [=] (const auto& h) {
  55. if constexpr (NPrivate::THasName<std::decay_t<decltype(h)>>::value) {
  56. return AsciiCompareIgnoreCase(h.Name(), TStringBuf("accept")) == 0;
  57. } else if (isPlainPair) {
  58. return AsciiCompareIgnoreCase(h.first, TStringBuf("accept")) == 0;
  59. }
  60. });
  61. if (it != std::end(headers)) {
  62. if constexpr (isPlainPair) {
  63. return FormatFromAcceptHeader(it->second);
  64. } else {
  65. return FormatFromAcceptHeader(it->Value());
  66. }
  67. }
  68. return EFormat::UNKNOWN;
  69. }
  70. } // namespace NMonitoring