forgejo-runner

git clone git://git.lin.moe/forgejo-runner.git

 1// Copyright 2022 The Gitea Authors. All rights reserved.
 2// SPDX-License-Identifier: MIT
 3
 4package client
 5
 6import (
 7	"context"
 8	"crypto/tls"
 9	"net/http"
10	"strings"
11
12	"code.gitea.io/actions-proto-go/ping/v1/pingv1connect"
13	"code.gitea.io/actions-proto-go/runner/v1/runnerv1connect"
14	"connectrpc.com/connect"
15)
16
17func getHTTPClient(endpoint string, insecure bool) *http.Client {
18	if strings.HasPrefix(endpoint, "https://") && insecure {
19		return &http.Client{
20			Transport: &http.Transport{
21				TLSClientConfig: &tls.Config{
22					InsecureSkipVerify: true,
23				},
24			},
25		}
26	}
27	return http.DefaultClient
28}
29
30// New returns a new runner client.
31func New(endpoint string, insecure bool, uuid, token, version string, opts ...connect.ClientOption) *HTTPClient {
32	baseURL := strings.TrimRight(endpoint, "/") + "/api/actions"
33
34	opts = append(opts, connect.WithInterceptors(connect.UnaryInterceptorFunc(func(next connect.UnaryFunc) connect.UnaryFunc {
35		return func(ctx context.Context, req connect.AnyRequest) (connect.AnyResponse, error) {
36			if uuid != "" {
37				req.Header().Set(UUIDHeader, uuid)
38			}
39			if token != "" {
40				req.Header().Set(TokenHeader, token)
41			}
42			// TODO: version will be removed from request header after Gitea 1.20 released.
43			if version != "" {
44				req.Header().Set(VersionHeader, version)
45			}
46			return next(ctx, req)
47		}
48	})))
49
50	return &HTTPClient{
51		PingServiceClient: pingv1connect.NewPingServiceClient(
52			getHTTPClient(endpoint, insecure),
53			baseURL,
54			opts...,
55		),
56		RunnerServiceClient: runnerv1connect.NewRunnerServiceClient(
57			getHTTPClient(endpoint, insecure),
58			baseURL,
59			opts...,
60		),
61		endpoint: endpoint,
62		insecure: insecure,
63	}
64}
65
66func (c *HTTPClient) Address() string {
67	return c.endpoint
68}
69
70func (c *HTTPClient) Insecure() bool {
71	return c.insecure
72}
73
74var _ Client = (*HTTPClient)(nil)
75
76// An HTTPClient manages communication with the runner API.
77type HTTPClient struct {
78	pingv1connect.PingServiceClient
79	runnerv1connect.RunnerServiceClient
80	endpoint string
81	insecure bool
82}