1
    2
    3
    4
    5
    6
    7
    8
    9
   10
   11
   12
   13
   14
   15
   16
   17
   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
   67
   68
   69
   70
   71
   72
   73
   74
   75
   76
   77
   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
  148
  149
  150
  151
  152
  153
  154
  155
  156
  157
  158
  159
  160
  161
  162
  163
  164
  165
  166
  167
  168
  169
  170
  171
  172
  173
  174
  175
  176
  177
  178
  179
  180
  181
  182
  183
  184
  185
  186
  187
  188
  189
  190
  191
  192
  193
  194
  195
  196
  197
  198
  199
  200
  201
  202
  203
  204
  205
  206
  207
  208
  209
  210
  211
  212
  213
  214
  215
  216
  217
  218
  219
  220
  221
  222
  223
  224
  225
  226
  227
  228
  229
  230
  231
  232
  233
  234
  235
  236
  237
  238
  239
  240
  241
  242
  243
  244
  245
  246
  247
  248
  249
  250
  251
  252
  253
  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
  280
  281
  282
  283
  284
  285
  286
  287
  288
  289
  290
  291
  292
  293
  294
  295
  296
  297
  298
  299
  300
  301
  302
  303
  304
  305
  306
  307
  308
  309
  310
  311
  312
  313
  314
  315
  316
  317
  318
  319
  320
  321
  322
  323
  324
  325
  326
  327
  328
  329
  330
  331
  332
  333
  334
  335
  336
  337
  338
  339
  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
  369
  370
  371

base / metrics / field_trial_params.h [blame]

// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/40284755): Remove this and spanify to fix the errors.
#pragma allow_unsafe_buffers
#endif

#ifndef BASE_METRICS_FIELD_TRIAL_PARAMS_H_
#define BASE_METRICS_FIELD_TRIAL_PARAMS_H_

#include <array>
#include <map>
#include <string>

#include "base/base_export.h"
#include "base/feature_list.h"
#include "base/memory/raw_ptr_exclusion.h"
#include "base/no_destructor.h"
#include "base/notreached.h"
#include "base/time/time.h"

namespace base {

namespace internal {

BASE_EXPORT bool IsFeatureParamWithCacheEnabled();

// A traits struct to manage the type for the default value in the following
// FeatureParam<> template. `std::string` needs to use a string literal instead
// of `std::string` to realize compile time construction.
template <typename T>
struct FeatureParamTraits {
  using DefaultValueType = T;
  using CacheStorageType = T;
  static CacheStorageType ToCacheStorageType(const T& value) {
    return value;
  }
  static constexpr T FromCacheStorageType(const CacheStorageType& storage) {
    return storage;
  }
};

template <>
struct FeatureParamTraits<std::string> {
  using DefaultValueType = const char*;
  using CacheStorageType = NoDestructor<std::string>;
  static CacheStorageType ToCacheStorageType(
      const std::string& value) {
    return CacheStorageType(value);
  }
  static constexpr std::string FromCacheStorageType(
      const CacheStorageType& storage) {
    return *storage;
  }
};

}  // namespace internal

// Key-value mapping type for field trial parameters.
typedef std::map<std::string, std::string> FieldTrialParams;

// Param string decoding function for AssociateFieldTrialParamsFromString().
typedef std::string (*FieldTrialParamsDecodeStringFunc)(const std::string& str);

// Unescapes special characters from the given string. Used in
// AssociateFieldTrialParamsFromString() as one of the feature params decoding
// functions.
BASE_EXPORT std::string UnescapeValue(const std::string& value);

// Associates the specified set of key-value |params| with the field trial
// specified by |trial_name| and |group_name|. Fails and returns false if the
// specified field trial already has params associated with it or the trial
// is already active (group() has been called on it). Thread safe.
BASE_EXPORT bool AssociateFieldTrialParams(const std::string& trial_name,
                                           const std::string& group_name,
                                           const FieldTrialParams& params);

// Provides a mechanism to associate multiple set of params to multiple groups
// with a formatted string as returned by FieldTrialList::AllParamsToString().
// |decode_data_func| allows specifying a custom decoding function.
BASE_EXPORT bool AssociateFieldTrialParamsFromString(
    const std::string& params_string,
    FieldTrialParamsDecodeStringFunc decode_data_func);

// Retrieves the set of key-value |params| for the specified field trial, based
// on its selected group. If the field trial does not exist or its selected
// group does not have any parameters associated with it, returns false and
// does not modify |params|. Calling this function will result in the field
// trial being marked as active if found (i.e. group() will be called on it),
// if it wasn't already. Thread safe.
BASE_EXPORT bool GetFieldTrialParams(const std::string& trial_name,
                                     FieldTrialParams* params);

// Retrieves the set of key-value |params| for the field trial associated with
// the specified |feature|. A feature is associated with at most one field
// trial and selected group. See  base/feature_list.h for more information on
// features. If the feature is not enabled, or if there's no associated params,
// returns false and does not modify |params|. Calling this function will
// result in the associated field trial being marked as active if found (i.e.
// group() will be called on it), if it wasn't already. Thread safe.
BASE_EXPORT bool GetFieldTrialParamsByFeature(const base::Feature& feature,
                                              FieldTrialParams* params);

// Retrieves a specific parameter value corresponding to |param_name| for the
// specified field trial, based on its selected group. If the field trial does
// not exist or the specified parameter does not exist, returns an empty
// string. Calling this function will result in the field trial being marked as
// active if found (i.e. group() will be called on it), if it wasn't already.
// Thread safe.
BASE_EXPORT std::string GetFieldTrialParamValue(const std::string& trial_name,
                                                const std::string& param_name);

// Retrieves a specific parameter value corresponding to |param_name| for the
// field trial associated with the specified |feature|. A feature is associated
// with at most one field trial and selected group. See base/feature_list.h for
// more information on features. If the feature is not enabled, or the
// specified parameter does not exist, returns an empty string. Calling this
// function will result in the associated field trial being marked as active if
// found (i.e. group() will be called on it), if it wasn't already. Thread safe.
BASE_EXPORT std::string GetFieldTrialParamValueByFeature(
    const base::Feature& feature,
    const std::string& param_name);

// Same as GetFieldTrialParamValueByFeature(). But internally relies on
// GetFieldTrialParamsByFeature to handle empty values in the map, and returns
// |default_value| only if |param_name| is not found in the map.
BASE_EXPORT std::string GetFieldTrialParamByFeatureAsString(
    const base::Feature& feature,
    const std::string& param_name,
    const std::string& default_value);

// Same as GetFieldTrialParamValueByFeature(). On top of that, it converts the
// string value into an int using base::StringToInt() and returns it, if
// successful. Otherwise, it returns |default_value|. If the string value is not
// empty and the conversion does not succeed, it produces a warning to LOG.
BASE_EXPORT int GetFieldTrialParamByFeatureAsInt(const base::Feature& feature,
                                                 const std::string& param_name,
                                                 int default_value);

// Same as GetFieldTrialParamValueByFeature(). On top of that, it converts the
// string value into a double using base::StringToDouble() and returns it, if
// successful. Otherwise, it returns |default_value|. If the string value is not
// empty and the conversion does not succeed, it produces a warning to LOG.
BASE_EXPORT double GetFieldTrialParamByFeatureAsDouble(
    const base::Feature& feature,
    const std::string& param_name,
    double default_value);

// Same as GetFieldTrialParamValueByFeature(). On top of that, it converts the
// string value into a boolean and returns it, if successful. Otherwise, it
// returns |default_value|. The only string representations accepted here are
// "true" and "false". If the string value is not empty and the conversion does
// not succeed, it produces a warning to LOG.
BASE_EXPORT bool GetFieldTrialParamByFeatureAsBool(
    const base::Feature& feature,
    const std::string& param_name,
    bool default_value);

// Same as GetFieldTrialParamValueByFeature(). On top of that, it converts the
// string value into a base::TimeDelta and returns it, if successful. Otherwise,
// it returns `default_value`. If the string value is not empty and the
// conversion does not succeed, it produces a warning to LOG.
BASE_EXPORT base::TimeDelta GetFieldTrialParamByFeatureAsTimeDelta(
    const Feature& feature,
    const std::string& param_name,
    base::TimeDelta default_value);

// Shared declaration for various FeatureParam<T> types.
//
// This template is defined for the following types T:
//   bool
//   int
//   size_t
//   double
//   std::string
//   enum types
//   base::TimeDelta
//
// Attempting to use it with any other type is a compile error.
//
// Getting a param value from a FeatureParam<T> will have the same semantics as
// GetFieldTrialParamValueByFeature(), see that function's comments for details.
// `cache_getter` is used to provide a dedicated getter tbat is used to give a
// local cache to the FeatureParam. Usually, this is automatically generated and
// provided via BASE_FEATURE_PARAM() or BASE_FEATURE_ENUM_PARAM() macro.
//
// Example to declares a double-valued parameter.
//
//     constexpr FeatureParam<double> kAssistantTriggerThreshold = {
//         &kAssistantFeature, "trigger_threshold", 0.10};
//
// If the feature is not enabled, the parameter is not set, or set to an invalid
// value, then Get() will return the default value.
template <typename T, bool IsEnum = std::is_enum_v<T>>
struct FeatureParam {
  using DefaultValueType =
      typename internal::FeatureParamTraits<T>::DefaultValueType;

  // Prevent use of FeatureParam<> with unsupported types (e.g. void*). Uses T
  // in its definition so that evaluation is deferred until the template is
  // instantiated.
  static_assert(std::is_same_v<bool, T> || std::is_same_v<int, T> ||
                    std::is_same_v<size_t, T> || std::is_same_v<double, T> ||
                    std::is_same_v<std::string, T> ||
                    std::is_same_v<base::TimeDelta, T>,
                "Unsupported FeatureParam<> type");

  constexpr FeatureParam(const Feature* feature,
                         const char* name,
                         DefaultValueType default_value,
                         T (*cache_getter)(const FeatureParam<T>*) = nullptr)
      : feature(feature),
        name(name),
        default_value(default_value),
        cache_getter(cache_getter) {}

  // Calling Get() or GetWithoutCache() will activate the field trial associated
  // with |feature|. See GetFieldTrialParamValueByFeature() for more details.
  BASE_EXPORT T Get() const {
    if (internal::IsFeatureParamWithCacheEnabled() && cache_getter) {
      return cache_getter(this);
    }
    return GetWithoutCache();
  }
  BASE_EXPORT T GetWithoutCache() const;

  // RAW_PTR_EXCLUSION: #global-scope
  RAW_PTR_EXCLUSION const Feature* const feature;
  const char* const name;
  const DefaultValueType default_value;
  T (*const cache_getter)(const FeatureParam<T>*);
};

// Declarations for GetWithoutCache() specializations and explicit
// instantiations for the FeatureParam<> to ensure instantiating them
// in the base components to export them.
template <>
bool FeatureParam<bool>::GetWithoutCache() const;
template struct FeatureParam<bool>;
template struct internal::FeatureParamTraits<bool>;

template <>
int FeatureParam<int>::GetWithoutCache() const;
template struct FeatureParam<int>;
template struct internal::FeatureParamTraits<int>;

template <>
size_t FeatureParam<size_t>::GetWithoutCache() const;
template struct FeatureParam<size_t>;
template struct internal::FeatureParamTraits<size_t>;

template <>
double FeatureParam<double>::GetWithoutCache() const;
template struct FeatureParam<double>;
template struct internal::FeatureParamTraits<double>;

template <>
std::string FeatureParam<std::string>::GetWithoutCache() const;
template struct FeatureParam<std::string>;

template <>
TimeDelta FeatureParam<TimeDelta>::GetWithoutCache() const;
template struct FeatureParam<TimeDelta>;
template struct internal::FeatureParamTraits<TimeDelta>;

BASE_EXPORT void LogInvalidEnumValue(const Feature& feature,
                                     const std::string& param_name,
                                     const std::string& value_as_string,
                                     int default_value_as_int);

// Feature param declaration for an enum, with associated options. Example:
//
//     constexpr FeatureParam<ShapeEnum>::Option kShapeParamOptions[] = {
//         {SHAPE_CIRCLE, "circle"},
//         {SHAPE_CYLINDER, "cylinder"},
//         {SHAPE_PAPERCLIP, "paperclip"}};
//     constexpr FeatureParam<ShapeEnum> kAssistantShapeParam = {
//         &kAssistantFeature, "shape", SHAPE_CIRCLE, &kShapeParamOptions};
//
// With this declaration, the parameter may be set to "circle", "cylinder", or
// "paperclip", and that will be translated to one of the three enum values. By
// default, or if the param is set to an unknown value, the parameter will be
// assumed to be SHAPE_CIRCLE.
template <typename Enum>
struct FeatureParam<Enum, true> {
  struct Option {
    constexpr Option(Enum value, const char* name) : value(value), name(name) {}

    const Enum value;
    const char* const name;
  };

  template <size_t option_count>
  constexpr FeatureParam(
      const Feature* feature,
      const char* name,
      const Enum default_value,
      const std::array<Option, option_count>& options,
      Enum (*cache_getter)(const FeatureParam<Enum>*) = nullptr)
      : feature(feature),
        name(name),
        default_value(default_value),
        options(options.data()),
        option_count(option_count),
        cache_getter(cache_getter) {
    static_assert(option_count >= 1, "FeatureParam<enum> has no options");
  }

  template <size_t option_count>
  constexpr FeatureParam(
      const Feature* feature,
      const char* name,
      const Enum default_value,
      const Option (*options)[option_count],
      Enum (*cache_getter)(const FeatureParam<Enum>*) = nullptr)
      : feature(feature),
        name(name),
        default_value(default_value),
        options(*options),
        option_count(option_count),
        cache_getter(cache_getter) {
    static_assert(option_count >= 1, "FeatureParam<enum> has no options");
  }

  // Calling Get() or GetWithoutCache() will activate the field trial associated
  // with |feature|. See GetFieldTrialParamValueByFeature() for more details.
  Enum Get() const {
    if (internal::IsFeatureParamWithCacheEnabled() && cache_getter) {
      return cache_getter(this);
    }
    return GetWithoutCache();
  }
  Enum GetWithoutCache() const {
    std::string value = GetFieldTrialParamValueByFeature(*feature, name);
    if (value.empty()) {
      return default_value;
    }
    for (size_t i = 0; i < option_count; ++i) {
      if (value == options[i].name) {
        return options[i].value;
      }
    }
    LogInvalidEnumValue(*feature, name, value, static_cast<int>(default_value));
    return default_value;
  }

  // Returns the param-string for the given enum value.
  std::string GetName(Enum value) const {
    for (size_t i = 0; i < option_count; ++i) {
      if (value == options[i].value) {
        return options[i].name;
      }
    }
    NOTREACHED();
  }

  const raw_ptr<const base::Feature> feature;
  const char* const name;
  const Enum default_value;
  // TODO(crbug.com/40284755): Remove AllowPtrArithmetic if possible after
  // unsafe buffers have been evaluated.
  const raw_ptr<const Option, AllowPtrArithmetic> options;
  const size_t option_count;
  Enum (*const cache_getter)(const FeatureParam<Enum>*);
};

}  // namespace base

#endif  // BASE_METRICS_FIELD_TRIAL_PARAMS_H_