• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2016 gRPC authors.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15#
16# This is for the gRPC build system. This isn't intended to be used outsite of
17# the BUILD file for gRPC. It contains the mapping for the template system we
18# use to generate other platform's build system files.
19#
20# Please consider that there should be a high bar for additions and changes to
21# this file.
22# Each rule listed must be re-written for Google's internal build system, and
23# each change must be ported from one to the other.
24#
25
26"""
27Contains macros used throughout the repo.
28"""
29
30load("@build_bazel_rules_apple//apple:ios.bzl", "ios_unit_test")
31load("@build_bazel_rules_apple//apple/testing/default_runner:ios_test_runner.bzl", "ios_test_runner")
32load("@com_google_protobuf//bazel:upb_proto_library.bzl", "upb_proto_library", "upb_proto_reflection_library")
33load("@rules_proto//proto:defs.bzl", "proto_library")
34load("//bazel:cc_grpc_library.bzl", "cc_grpc_library")
35load("//bazel:copts.bzl", "GRPC_DEFAULT_COPTS")
36load("//bazel:experiments.bzl", "EXPERIMENTS", "EXPERIMENT_ENABLES", "EXPERIMENT_POLLERS")
37load("//bazel:test_experiments.bzl", "TEST_EXPERIMENTS", "TEST_EXPERIMENT_ENABLES", "TEST_EXPERIMENT_POLLERS")
38
39# The set of pollers to test against if a test exercises polling
40POLLERS = ["epoll1", "poll"]
41
42# The set of known EventEngines to test
43EVENT_ENGINES = {"default": {"tags": []}}
44
45def if_not_windows(a):
46    return select({
47        "//:windows": [],
48        "//:windows_msvc": [],
49        "//:windows_clang": [],
50        "//conditions:default": a,
51    })
52
53def if_windows(a):
54    return select({
55        "//:windows": a,
56        "//:windows_msvc": a,
57        "//:windows_clang": a,
58        "//conditions:default": [],
59    })
60
61def _get_external_deps(external_deps):
62    ret = []
63    for dep in external_deps:
64        if dep.startswith("@"):
65            ret.append(dep)
66        elif dep == "address_sorting":
67            ret.append("//third_party/address_sorting")
68        elif dep == "xxhash":
69            ret.append("//third_party/xxhash")
70        elif dep == "cares":
71            ret += select({
72                "//:grpc_no_ares": [],
73                "//conditions:default": ["//third_party:cares"],
74            })
75        elif dep == "cronet_c_for_grpc":
76            ret.append("//third_party/objective_c/Cronet:cronet_c_for_grpc")
77        elif dep.startswith("absl/"):
78            ret.append("@com_google_absl//" + dep)
79        elif dep.startswith("google/"):
80            ret.append("@com_google_googleapis//" + dep)
81        elif dep.startswith("otel/"):
82            ret.append(dep.replace("otel/", "@io_opentelemetry_cpp//"))
83        elif dep.startswith("google_cloud_cpp"):
84            ret.append(dep.replace("google_cloud_cpp", "@google_cloud_cpp//"))
85        elif dep == "libprotobuf_mutator":
86            ret.append("@com_google_libprotobuf_mutator//:libprotobuf_mutator")
87        else:
88            ret.append("//third_party:" + dep)
89    return ret
90
91def _update_visibility(visibility):
92    if visibility == None:
93        return None
94
95    # Visibility rules prefixed with '@grpc:' are used to flag different visibility rule
96    # classes upstream.
97    PUBLIC = ["//visibility:public"]
98    PRIVATE = ["//:__subpackages__"]
99    VISIBILITY_TARGETS = {
100        "alt_grpc++_base_legacy": PRIVATE,
101        "alt_grpc_base_legacy": PRIVATE,
102        "alt_grpc++_base_unsecure_legacy": PRIVATE,
103        "alts_frame_protector": PRIVATE,
104        "channelz": PRIVATE,
105        "chaotic_good": PRIVATE,
106        "client_channel": PRIVATE,
107        "cli": PRIVATE,
108        "core_credentials": PRIVATE,
109        "debug_location": PRIVATE,
110        "endpoint_tests": PRIVATE,
111        "exec_ctx": PRIVATE,
112        "gpr_public_hdrs": PRIVATE,
113        "grpclb": PRIVATE,
114        "grpc_experiments": PRIVATE,
115        "grpc_opencensus_plugin": PUBLIC,
116        "grpc_public_hdrs": PRIVATE,
117        "grpcpp_gcp_observability": PUBLIC,
118        "grpc_resolver_fake": PRIVATE,
119        "grpc++_public_hdrs": PUBLIC,
120        "http": PRIVATE,
121        "httpcli": PRIVATE,
122        "iomgr_internal_errqueue": PRIVATE,
123        "iomgr_buffer_list": PRIVATE,
124        "json_reader_legacy": PRIVATE,
125        "latent_see": PRIVATE,
126        "otel_plugin": PRIVATE,
127        "public": PUBLIC,
128        "ref_counted_ptr": PRIVATE,
129        "tcp_tracer": PRIVATE,
130        "trace": PRIVATE,
131        "tsi_interface": PRIVATE,
132        "tsi": PRIVATE,
133        "xds": PRIVATE,
134        "xds_client_core": PRIVATE,
135        "xds_end2end_test_utils": PRIVATE,
136        "grpc_python_observability": PRIVATE,
137        "event_engine_base_hdrs": PRIVATE,
138        "useful": PRIVATE,
139    }
140    final_visibility = []
141    for rule in visibility:
142        if rule.startswith("@grpc:"):
143            for replacement in VISIBILITY_TARGETS[rule[len("@grpc:"):]]:
144                final_visibility.append(replacement)
145        else:
146            final_visibility.append(rule)
147    return [x for x in final_visibility]
148
149def _include_prefix():
150    include_prefix = ""
151    if native.package_name():
152        for _ in native.package_name().split("/"):
153            include_prefix += "../"
154    return include_prefix
155
156def grpc_cc_library(
157        name,
158        srcs = [],
159        public_hdrs = [],
160        hdrs = [],
161        external_deps = [],
162        defines = [],
163        deps = [],
164        select_deps = None,
165        standalone = False,
166        language = "C++",
167        testonly = False,
168        visibility = None,
169        alwayslink = 0,
170        data = [],
171        tags = [],
172        linkopts = [],
173        linkstatic = False):
174    """An internal wrapper around cc_library.
175
176    Args:
177      name: The name of the library.
178      srcs: The source files.
179      public_hdrs: The public headers.
180      hdrs: The headers.
181      external_deps: External dependencies to be resolved.
182      defines: Build defines to use.
183      deps: cc_library deps.
184      select_deps: deps included conditionally.
185      standalone: Unused.
186      language: The language of the library, e.g. C, C++.
187      testonly: Whether the target is for tests only.
188      visibility: The visibility of the target.
189      alwayslink: Whether to enable alwayslink on the cc_library.
190      data: Data dependencies.
191      tags: Tags to apply to the rule.
192      linkopts: Extra libraries to link.
193      linkstatic: Whether to enable linkstatic on the cc_library.
194    """
195    visibility = _update_visibility(visibility)
196    copts = []
197    if language.upper() == "C":
198        copts = copts + if_not_windows(["-std=c11"])
199    linkopts = linkopts + if_not_windows(["-pthread"]) + if_windows(["-defaultlib:ws2_32.lib"])
200    if select_deps:
201        for select_deps_entry in select_deps:
202            deps += select(select_deps_entry)
203    include_prefix = _include_prefix()
204    native.cc_library(
205        name = name,
206        srcs = srcs,
207        defines = defines +
208                  select({
209                      "//:grpc_no_ares": ["GRPC_ARES=0"],
210                      "//conditions:default": [],
211                  }) +
212                  select({
213                      "//:remote_execution": ["GRPC_PORT_ISOLATED_RUNTIME=1"],
214                      "//conditions:default": [],
215                  }) +
216                  select({
217                      "//:grpc_allow_exceptions": ["GRPC_ALLOW_EXCEPTIONS=1"],
218                      "//:grpc_disallow_exceptions": ["GRPC_ALLOW_EXCEPTIONS=0"],
219                      "//conditions:default": [],
220                  }),
221        hdrs = hdrs + public_hdrs,
222        deps = deps + _get_external_deps(external_deps),
223        copts = GRPC_DEFAULT_COPTS + copts,
224        visibility = visibility,
225        testonly = testonly,
226        linkopts = linkopts,
227        includes = [
228            include_prefix + "include",
229            include_prefix + "src/core/ext/upb-gen",  # Once upb code-gen issue is resolved, remove this.
230            include_prefix + "src/core/ext/upbdefs-gen",  # Once upb code-gen issue is resolved, remove this.
231        ],
232        alwayslink = alwayslink,
233        data = data,
234        tags = tags,
235        linkstatic = linkstatic,
236    )
237
238def grpc_proto_plugin(name, srcs = [], deps = []):
239    native.cc_binary(
240        name = name,
241        srcs = srcs,
242        deps = deps,
243    )
244
245def grpc_internal_proto_library(
246        name,
247        srcs = [],
248        deps = [],
249        visibility = None,
250        has_services = False):  # buildifier: disable=unused-variable
251    proto_library(
252        name = name,
253        srcs = srcs,
254        deps = deps,
255        visibility = visibility,
256    )
257
258def grpc_cc_proto_library(name, deps = [], visibility = None):
259    native.cc_proto_library(name = name, deps = deps, visibility = visibility)
260
261# DO NOT USE -- callers should instead be changed to use separate
262# grpc_internal_proto_library(), grpc_cc_proto_library(), and
263# grpc_cc_grpc_library() rules.
264def grpc_proto_library(
265        name,
266        srcs = [],
267        deps = [],
268        visibility = None,
269        well_known_protos = False,
270        has_services = True,
271        use_external = False,
272        generate_mocks = False):
273    cc_grpc_library(
274        name = name,
275        srcs = srcs,
276        deps = deps,
277        visibility = visibility,
278        well_known_protos = well_known_protos,
279        proto_only = not has_services,
280        use_external = use_external,
281        generate_mocks = generate_mocks,
282    )
283
284def grpc_cc_grpc_library(
285        name,
286        srcs = [],
287        deps = [],
288        visibility = None,
289        generate_mocks = False):
290    """A wrapper around cc_grpc_library that forces grpc_only=True.
291
292    Callers are expected to have their own proto_library() and
293    cc_proto_library() rules and then use this rule to produce only the
294    gRPC generated code.
295    """
296    cc_grpc_library(
297        name = name,
298        srcs = srcs,
299        deps = deps,
300        visibility = visibility,
301        generate_mocks = generate_mocks,
302        grpc_only = True,
303    )
304
305def ios_cc_test(
306        name,
307        tags = [],
308        **kwargs):
309    """An ios C++ test target.
310
311    Args:
312      name: The name of the test.
313      tags: The tags to apply to the test.
314      **kwargs: All other arguments to apply.
315    """
316    test_lib_ios = name + "_test_lib_ios"
317    ios_tags = tags + ["manual", "ios_cc_test"]
318    test_runner = "ios_x86_64_sim_runner_" + name
319    ios_test_runner(
320        name = test_runner,
321        device_type = "iPhone X",
322    )
323    if not any([t for t in tags if t.startswith("no_test_ios")]):
324        native.objc_library(
325            name = test_lib_ios,
326            srcs = kwargs.get("srcs"),
327            deps = kwargs.get("deps"),
328            copts = kwargs.get("copts"),
329            data = kwargs.get("data"),
330            tags = ios_tags,
331            alwayslink = 1,
332            testonly = 1,
333        )
334        ios_test_deps = [":" + test_lib_ios]
335        ios_unit_test(
336            name = name + "_on_ios",
337            size = kwargs.get("size"),
338            data = kwargs.get("data"),
339            tags = ios_tags,
340            minimum_os_version = "11.0",
341            runner = test_runner,
342            deps = ios_test_deps,
343        )
344
345def expand_poller_config(name, srcs, deps, tags, args, exclude_pollers, uses_polling, uses_event_engine, flaky):
346    """Common logic used to parameterize tests for every poller and EventEngine.
347
348    Used by expand_tests (repeatedly) to form base lists of pollers for each experiment.
349
350    Args:
351        name: base name of the test
352        srcs: source files
353        deps: base deps
354        tags: base tags
355        args: base args
356        flaky: base flaky
357        exclude_pollers: list of poller names to exclude for this set of tests.
358        uses_polling: set to False if the test is not sensitive to polling methodology.
359        uses_event_engine: set to False if the test is not sensitive to
360            EventEngine implementation differences
361
362    Returns:
363        A list of dictionaries containing modified values of name, srcs, deps, tags, and args.
364    """
365
366    poller_config = []
367
368    # See work_stealing_thread_pool.cc for details.
369    default_env = {"GRPC_THREAD_POOL_VERBOSE_FAILURES": "true"}
370
371    if not uses_polling:
372        tags = tags + ["no_uses_polling"]
373
374        poller_config.append({
375            "name": name,
376            "srcs": srcs,
377            "deps": deps,
378            "tags": tags,
379            "args": args,
380            "flaky": flaky,
381            "env": default_env,
382        })
383    else:
384        # On linux we run the same test with the default EventEngine, once for each
385        # poller
386        for poller in POLLERS:
387            if poller in exclude_pollers:
388                continue
389            poller_config.append({
390                "name": name + "@poller=" + poller,
391                "srcs": srcs,
392                "deps": deps,
393                "tags": (tags + EVENT_ENGINES["default"]["tags"] + [
394                    "no_windows",
395                    "no_mac",
396                    "bazel_only",
397                ]),
398                "args": args,
399                "env": {
400                    "GRPC_POLL_STRATEGY": poller,
401                } | default_env,
402                "flaky": flaky,
403            })
404
405        # Now generate one test for each subsequent EventEngine, all using the
406        # default poller. These tests will have `@engine=<name>` appended to the
407        # test target name. If a test target name has no `@engine=<name>` component,
408        # that indicates that the default EventEngine is being used.
409        if not uses_event_engine:
410            # The poller tests exercise the default engine on Linux. This test
411            # handles other platforms.
412            poller_config.append({
413                "name": name,
414                "srcs": srcs,
415                "deps": deps,
416                "tags": tags + ["no_linux"],
417                "args": args,
418                "env": default_env,
419                "flaky": flaky,
420            })
421        else:
422            for engine_name, engine in EVENT_ENGINES.items():
423                test_name = name + "@engine=" + engine_name
424                test_tags = tags + engine["tags"] + ["bazel_only"]
425                test_args = args + ["--engine=" + engine_name]
426                if engine_name == "default":
427                    # The poller tests exercise the default engine on Linux.
428                    # This test handles other platforms.
429                    test_name = name
430                    test_tags = tags + engine["tags"] + ["no_linux"]
431                    test_args = args
432                poller_config.append({
433                    "name": test_name,
434                    "srcs": srcs,
435                    "deps": deps,
436                    "tags": test_tags,
437                    "args": test_args,
438                    "env": default_env,
439                    "flaky": flaky,
440                })
441
442    return poller_config
443
444def expand_tests(name, srcs, deps, tags, args, exclude_pollers, uses_polling, uses_event_engine, flaky):
445    """Common logic used to parameterize tests for every poller and EventEngine and experiment.
446
447    Args:
448        name: base name of the test
449        srcs: source files
450        deps: base deps
451        tags: base tags
452        args: base args
453        flaky: base flaky
454        exclude_pollers: list of poller names to exclude for this set of tests.
455        uses_polling: set to False if the test is not sensitive to polling methodology.
456        uses_event_engine: set to False if the test is not sensitive to
457            EventEngine implementation differences
458
459    Returns:
460        A list of dictionaries containing modified values of name, srcs, deps, tags, and args.
461    """
462
463    experiments = {}
464
465    # buildifier: disable=uninitialized
466    def _populate_experiments_platform_config(config, platform_experiments_map):
467        for platform, experiments_on_platform in platform_experiments_map.items():
468            for mode, tag_to_experiments in experiments_on_platform.items():
469                if mode not in config:
470                    config[mode] = {}
471                for tag in tags:
472                    if tag not in tag_to_experiments:
473                        continue
474                    for experiment in tag_to_experiments[tag]:
475                        if experiment not in config[mode]:
476                            config[mode][experiment] = []
477                        config[mode][experiment].append(platform)
478
479    _populate_experiments_platform_config(experiments, EXPERIMENTS)
480    _populate_experiments_platform_config(experiments, TEST_EXPERIMENTS)
481
482    mode_config = {
483        # format: <mode>: (enabled_target_tags, disabled_target_tags)
484        "on": (None, []),
485        "off": ([], None),
486    }
487
488    must_have_tags = [
489        # We don't run experiments on cmake builds
490        "bazel_only",
491        # Nor on mac
492        "no_mac",
493        # Nor on arm64
494        "no_arm64",
495    ]
496
497    def _update_experiments_platform_test_tags(tags, platforms):
498        if "posix" not in platforms:
499            if "no_linux" not in tags:
500                tags.append("no_linux")
501            if "no_mac" not in tags:
502                tags.append("no_mac")
503        if "windows" not in platforms:
504            if "no_windows" not in tags:
505                tags.append("no_windows")
506        if "ios" not in platforms:
507            if "no_test_ios" not in tags:
508                tags.append("no_test_ios")
509        return tags
510
511    base_params = {
512        "name": name,
513        "srcs": srcs,
514        "deps": deps,
515        "tags": tags,
516        "args": args,
517        "exclude_pollers": exclude_pollers,
518        "uses_polling": uses_polling,
519        "uses_event_engine": uses_event_engine,
520        "flaky": flaky,
521    }
522
523    experiment_config = expand_poller_config(**base_params)
524    experiment_enables = {k: v for k, v in EXPERIMENT_ENABLES.items() + TEST_EXPERIMENT_ENABLES.items()}
525    experiment_pollers = EXPERIMENT_POLLERS + TEST_EXPERIMENT_POLLERS
526    for mode, config in mode_config.items():
527        enabled_tags, disabled_tags = config
528        if enabled_tags != None:
529            for experiment in experiments[mode].keys():
530                experiment_params = dict(base_params)
531                experiment_params["uses_polling"] = uses_polling and (experiment in experiment_pollers)
532                for config in expand_poller_config(**experiment_params):
533                    config = dict(config)
534                    config["name"] = config["name"] + "@experiment=" + experiment
535                    env = dict(config["env"])
536                    env["GRPC_EXPERIMENTS"] = experiment_enables[experiment]
537                    env["GRPC_CI_EXPERIMENTS"] = "1"
538                    config["env"] = env
539                    tags = config["tags"] + ["experiment_variation"]
540                    for tag in must_have_tags + enabled_tags:
541                        if tag not in tags:
542                            tags = tags + [tag]
543                    config["tags"] = _update_experiments_platform_test_tags(tags, experiments[mode][experiment])
544                    config["flaky"] = True
545                    experiment_config.append(config)
546        if disabled_tags != None:
547            for experiment in experiments[mode].keys():
548                experiment_params = dict(base_params)
549                experiment_params["uses_polling"] = uses_polling and (experiment in experiment_pollers)
550                for config in expand_poller_config(**experiment_params):
551                    config = dict(config)
552                    config["name"] = config["name"] + "@experiment=no_" + experiment
553                    env = dict(config["env"])
554                    env["GRPC_EXPERIMENTS"] = "-" + experiment
555                    env["GRPC_CI_EXPERIMENTS"] = "1"
556                    config["env"] = env
557                    tags = config["tags"] + ["experiment_variation"]
558                    for tag in must_have_tags + disabled_tags:
559                        if tag not in tags:
560                            tags = tags + [tag]
561                    config["tags"] = _update_experiments_platform_test_tags(tags, experiments[mode][experiment])
562                    experiment_config.append(config)
563    return experiment_config
564
565def grpc_cc_test(name, srcs = [], deps = [], external_deps = [], args = [], data = [], uses_polling = True, language = "C++", size = "medium", timeout = None, tags = [], exec_compatible_with = [], exec_properties = {}, shard_count = None, flaky = None, copts = [], linkstatic = None, exclude_pollers = [], uses_event_engine = True):
566    """A cc_test target for use in the gRPC repo.
567
568    Args:
569        name: The name of the test.
570        srcs: The source files.
571        deps: The target deps.
572        external_deps: The external deps.
573        args: The args to supply to the test binary.
574        data: Data dependencies.
575        uses_polling: Whether the test uses polling.
576        language: The language of the test, e.g C, C++.
577        size: The size of the test.
578        timeout: The test timeout.
579        tags: The tags for the test.
580        exec_compatible_with: A list of constraint values that must be
581            satisfied for the platform.
582        exec_properties: A dictionary of strings that will be added to the
583            exec_properties of a platform selected for this target.
584        shard_count: The number of shards for this test.
585        flaky: Whether this test is flaky.
586        copts: Add these to the compiler invocation.
587        linkstatic: link the binary in static mode
588        exclude_pollers: list of poller names to exclude for this set of tests.
589        uses_event_engine: set to False if the test is not sensitive to
590            EventEngine implementation differences
591    """
592    if language.upper() == "C":
593        copts = copts + if_not_windows(["-std=c11"])
594
595    core_deps = deps + _get_external_deps(external_deps) + ["//test/core/test_util:grpc_suppressions"]
596
597    # Test args for all tests
598    test_args = {
599        "data": data,
600        "copts": GRPC_DEFAULT_COPTS + copts,
601        "linkopts": if_not_windows(["-pthread"]) + if_windows(["-defaultlib:ws2_32.lib"]),
602        "size": size,
603        "timeout": timeout,
604        "exec_compatible_with": exec_compatible_with,
605        "exec_properties": exec_properties,
606        "shard_count": shard_count,
607        "linkstatic": linkstatic,
608    }
609
610    if "grpc-fuzzer" not in tags and "no_test_ios" not in tags:
611        ios_cc_test(
612            name = name,
613            srcs = srcs,
614            tags = tags,
615            deps = core_deps,
616            args = args,
617            flaky = True,
618            **test_args
619        )
620
621    native.cc_library(
622        name = "%s_TEST_LIBRARY" % name,
623        testonly = 1,
624        srcs = srcs,
625        deps = core_deps,
626        tags = tags,
627        alwayslink = 1,
628    )
629
630    for poller_config in expand_tests(name, srcs, core_deps, tags, args, exclude_pollers, uses_polling, uses_event_engine, flaky):
631        if poller_config["srcs"] != srcs:
632            fail("srcs changed")
633        if poller_config["deps"] != core_deps:
634            fail("deps changed: %r --> %r" % (deps, poller_config["deps"]))
635        native.cc_test(
636            name = poller_config["name"],
637            deps = ["%s_TEST_LIBRARY" % name],
638            tags = poller_config["tags"],
639            args = poller_config["args"],
640            env = poller_config["env"],
641            flaky = poller_config["flaky"],
642            **test_args
643        )
644
645def grpc_cc_binary(name, srcs = [], deps = [], external_deps = [], args = [], data = [], language = "C++", testonly = False, linkshared = False, linkopts = [], tags = [], features = [], visibility = None):
646    """Generates a cc_binary for use in the gRPC repo.
647
648    Args:
649      name: The name of the target.
650      srcs: The source files.
651      deps: The dependencies.
652      external_deps: The external dependencies.
653      args: The arguments to supply to the binary.
654      data: The data dependencies.
655      language: The language of the binary, e.g. C, C++.
656      testonly: Whether the binary is for tests only.
657      linkshared: Enables linkshared on the binary.
658      linkopts: linkopts to supply to the cc_binary.
659      tags: Tags to apply to the target.
660      features: features to be supplied to the cc_binary.
661      visibility: The visibility of the target.
662    """
663    visibility = _update_visibility(visibility)
664    copts = []
665    if language.upper() == "C":
666        copts = ["-std=c11"]
667    native.cc_binary(
668        name = name,
669        srcs = srcs,
670        args = args,
671        data = data,
672        testonly = testonly,
673        linkshared = linkshared,
674        deps = deps + _get_external_deps(external_deps) + ["//test/core/test_util:grpc_suppressions"],
675        copts = GRPC_DEFAULT_COPTS + copts,
676        linkopts = if_not_windows(["-pthread"]) + linkopts,
677        tags = tags,
678        features = features,
679        visibility = visibility,
680    )
681
682# buildifier: disable=unnamed-macro
683def grpc_generate_one_off_targets():
684    # In open-source, grpc_objc* libraries depend directly on //:grpc
685    native.alias(
686        name = "grpc_objc",
687        actual = "//:grpc",
688    )
689    native.config_setting(
690        name = "windows_other",
691        values = {"define": "GRPC_WINDOWS_OTHER=1"},
692    )
693
694def grpc_generate_objc_one_off_targets():
695    pass
696
697def grpc_generate_one_off_internal_targets():
698    pass
699
700def grpc_sh_test(name, srcs = [], args = [], data = [], uses_polling = True, size = "medium", timeout = None, tags = [], exec_compatible_with = [], exec_properties = {}, shard_count = None, flaky = None, exclude_pollers = [], uses_event_engine = True):
701    """Execute an sh_test for every <poller> x <EventEngine> combination
702
703    Args:
704        name: The name of the test.
705        srcs: The source files.
706        args: The args to supply to the test binary.
707        data: Data dependencies.
708        uses_polling: Whether the test uses polling.
709        size: The size of the test.
710        timeout: The test timeout.
711        tags: The tags for the test.
712        exec_compatible_with: A list of constraint values that must be
713            satisfied for the platform.
714        exec_properties: A dictionary of strings that will be added to the
715            exec_properties of a platform selected for this target.
716        shard_count: The number of shards for this test.
717        flaky: Whether this test is flaky.
718        exclude_pollers: list of poller names to exclude for this set of tests.
719        uses_event_engine: set to False if the test is not sensitive to
720            EventEngine implementation differences
721    """
722    test_args = {
723        "data": data,
724        "size": size,
725        "timeout": timeout,
726        "exec_compatible_with": exec_compatible_with,
727        "exec_properties": exec_properties,
728        "shard_count": shard_count,
729    }
730
731    for poller_config in expand_tests(name, srcs, [], tags, args, exclude_pollers, uses_polling, uses_event_engine, flaky):
732        native.sh_test(
733            name = poller_config["name"],
734            srcs = poller_config["srcs"],
735            deps = poller_config["deps"],
736            tags = poller_config["tags"],
737            args = poller_config["args"],
738            env = poller_config["env"],
739            flaky = poller_config["flaky"],
740            **test_args
741        )
742
743def grpc_sh_binary(name, srcs, data = []):
744    native.sh_binary(
745        name = name,
746        srcs = srcs,
747        data = data,
748    )
749
750def grpc_py_binary(
751        name,
752        srcs,
753        data = [],
754        deps = [],
755        external_deps = [],
756        testonly = False,
757        python_version = "PY2",
758        **kwargs):
759    native.py_binary(
760        name = name,
761        srcs = srcs,
762        testonly = testonly,
763        data = data,
764        deps = deps + _get_external_deps(external_deps),
765        python_version = python_version,
766        **kwargs
767    )
768
769def grpc_package(name, visibility = "private", features = []):
770    """Creates a package.
771
772    Args:
773        name: The name of the target
774        visibility: The visibility of the target.
775        features: The features to enable.
776    """
777    if visibility == "tests":
778        visibility = ["//test:__subpackages__", "//src/proto/grpc/testing:__subpackages__"]
779    elif visibility == "public":
780        visibility = ["//visibility:public"]
781    elif visibility == "private":
782        visibility = []
783    else:
784        fail("Unknown visibility " + visibility)
785
786    if len(visibility) != 0:
787        # buildifier: disable=native-package
788        native.package(
789            default_visibility = visibility,
790            features = features,
791        )
792
793def grpc_filegroup(name, srcs, **kwargs):
794    native.filegroup(
795        name = name,
796        srcs = srcs,
797        **kwargs
798    )
799
800def grpc_objc_library(
801        name,
802        srcs = [],
803        hdrs = [],
804        non_arc_srcs = [],
805        textual_hdrs = [],
806        testonly = False,
807        data = [],
808        deps = [],
809        defines = [],
810        sdk_frameworks = [],
811        includes = [],
812        visibility = ["//visibility:public"]):
813    """The grpc version of objc_library, only used for the Objective-C library compilation
814
815    Args:
816        name: name of target
817        hdrs: public headers
818        srcs: all source files (.m)
819        non_arc_srcs: list of Objective-C files that DO NOT use ARC.
820        textual_hdrs: private headers
821        testonly: Whether the binary is for tests only.
822        data: any other bundle resources
823        defines: preprocessors
824        sdk_frameworks: sdks
825        includes: added to search path, always [the path to objc directory]
826        deps: dependencies
827        visibility: visibility, default to public
828    """
829
830    native.objc_library(
831        name = name,
832        hdrs = hdrs,
833        srcs = srcs,
834        non_arc_srcs = non_arc_srcs,
835        textual_hdrs = textual_hdrs,
836        copts = GRPC_DEFAULT_COPTS + ["-ObjC++", "-std=gnu++17"],
837        testonly = testonly,
838        data = data,
839        deps = deps,
840        defines = defines,
841        includes = includes,
842        sdk_frameworks = sdk_frameworks,
843        visibility = visibility,
844    )
845
846def grpc_upb_proto_library(name, deps):
847    upb_proto_library(name = name, deps = deps)
848
849def grpc_upb_proto_reflection_library(name, deps):
850    upb_proto_reflection_library(name = name, deps = deps)
851
852# buildifier: disable=unnamed-macro
853def python_config_settings():
854    native.config_setting(
855        name = "python3",
856        flag_values = {"@bazel_tools//tools/python:python_version": "PY3"},
857    )
858
859# buildifier: disable=unnamed-macro
860def grpc_clang_cl_settings():
861    native.platform(
862        name = "x64_windows-clang-cl",
863        constraint_values = [
864            "@platforms//cpu:x86_64",
865            "@platforms//os:windows",
866            "@bazel_tools//tools/cpp:clang-cl",
867        ],
868    )
869    native.config_setting(
870        name = "windows_clang",
871        constraint_values = [
872            "@platforms//cpu:x86_64",
873            "@platforms//os:windows",
874            "@bazel_tools//tools/cpp:clang-cl",
875        ],
876    )
877