requestconfig.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
  2. package requestconfig
  3. import (
  4. "bytes"
  5. "context"
  6. "encoding/json"
  7. "fmt"
  8. "io"
  9. "math"
  10. "math/rand"
  11. "mime"
  12. "net/http"
  13. "net/url"
  14. "runtime"
  15. "strconv"
  16. "strings"
  17. "time"
  18. "github.com/sst/opencode-sdk-go/internal"
  19. "github.com/sst/opencode-sdk-go/internal/apierror"
  20. "github.com/sst/opencode-sdk-go/internal/apiform"
  21. "github.com/sst/opencode-sdk-go/internal/apiquery"
  22. "github.com/sst/opencode-sdk-go/internal/param"
  23. )
  24. func getDefaultHeaders() map[string]string {
  25. return map[string]string{
  26. "User-Agent": fmt.Sprintf("Opencode/Go %s", internal.PackageVersion),
  27. }
  28. }
  29. func getNormalizedOS() string {
  30. switch runtime.GOOS {
  31. case "ios":
  32. return "iOS"
  33. case "android":
  34. return "Android"
  35. case "darwin":
  36. return "MacOS"
  37. case "window":
  38. return "Windows"
  39. case "freebsd":
  40. return "FreeBSD"
  41. case "openbsd":
  42. return "OpenBSD"
  43. case "linux":
  44. return "Linux"
  45. default:
  46. return fmt.Sprintf("Other:%s", runtime.GOOS)
  47. }
  48. }
  49. func getNormalizedArchitecture() string {
  50. switch runtime.GOARCH {
  51. case "386":
  52. return "x32"
  53. case "amd64":
  54. return "x64"
  55. case "arm":
  56. return "arm"
  57. case "arm64":
  58. return "arm64"
  59. default:
  60. return fmt.Sprintf("other:%s", runtime.GOARCH)
  61. }
  62. }
  63. func getPlatformProperties() map[string]string {
  64. return map[string]string{
  65. "X-Stainless-Lang": "go",
  66. "X-Stainless-Package-Version": internal.PackageVersion,
  67. "X-Stainless-OS": getNormalizedOS(),
  68. "X-Stainless-Arch": getNormalizedArchitecture(),
  69. "X-Stainless-Runtime": "go",
  70. "X-Stainless-Runtime-Version": runtime.Version(),
  71. }
  72. }
  73. type RequestOption interface {
  74. Apply(*RequestConfig) error
  75. }
  76. type RequestOptionFunc func(*RequestConfig) error
  77. type PreRequestOptionFunc func(*RequestConfig) error
  78. func (s RequestOptionFunc) Apply(r *RequestConfig) error { return s(r) }
  79. func (s PreRequestOptionFunc) Apply(r *RequestConfig) error { return s(r) }
  80. func NewRequestConfig(ctx context.Context, method string, u string, body interface{}, dst interface{}, opts ...RequestOption) (*RequestConfig, error) {
  81. var reader io.Reader
  82. contentType := "application/json"
  83. hasSerializationFunc := false
  84. if body, ok := body.(json.Marshaler); ok {
  85. content, err := body.MarshalJSON()
  86. if err != nil {
  87. return nil, err
  88. }
  89. reader = bytes.NewBuffer(content)
  90. hasSerializationFunc = true
  91. }
  92. if body, ok := body.(apiform.Marshaler); ok {
  93. var (
  94. content []byte
  95. err error
  96. )
  97. content, contentType, err = body.MarshalMultipart()
  98. if err != nil {
  99. return nil, err
  100. }
  101. reader = bytes.NewBuffer(content)
  102. hasSerializationFunc = true
  103. }
  104. if body, ok := body.(apiquery.Queryer); ok {
  105. hasSerializationFunc = true
  106. params := body.URLQuery().Encode()
  107. if params != "" {
  108. u = u + "?" + params
  109. }
  110. }
  111. if body, ok := body.([]byte); ok {
  112. reader = bytes.NewBuffer(body)
  113. hasSerializationFunc = true
  114. }
  115. if body, ok := body.(io.Reader); ok {
  116. reader = body
  117. hasSerializationFunc = true
  118. }
  119. // Fallback to json serialization if none of the serialization functions that we expect
  120. // to see is present.
  121. if body != nil && !hasSerializationFunc {
  122. content, err := json.Marshal(body)
  123. if err != nil {
  124. return nil, err
  125. }
  126. reader = bytes.NewBuffer(content)
  127. }
  128. req, err := http.NewRequestWithContext(ctx, method, u, nil)
  129. if err != nil {
  130. return nil, err
  131. }
  132. if reader != nil {
  133. req.Header.Set("Content-Type", contentType)
  134. }
  135. req.Header.Set("Accept", "application/json")
  136. req.Header.Set("X-Stainless-Retry-Count", "0")
  137. req.Header.Set("X-Stainless-Timeout", "0")
  138. for k, v := range getDefaultHeaders() {
  139. req.Header.Add(k, v)
  140. }
  141. for k, v := range getPlatformProperties() {
  142. req.Header.Add(k, v)
  143. }
  144. cfg := RequestConfig{
  145. MaxRetries: 2,
  146. Context: ctx,
  147. Request: req,
  148. HTTPClient: http.DefaultClient,
  149. Body: reader,
  150. }
  151. cfg.ResponseBodyInto = dst
  152. err = cfg.Apply(opts...)
  153. if err != nil {
  154. return nil, err
  155. }
  156. // This must run after `cfg.Apply(...)` above in case the request timeout gets modified. We also only
  157. // apply our own logic for it if it's still "0" from above. If it's not, then it was deleted or modified
  158. // by the user and we should respect that.
  159. if req.Header.Get("X-Stainless-Timeout") == "0" {
  160. if cfg.RequestTimeout == time.Duration(0) {
  161. req.Header.Del("X-Stainless-Timeout")
  162. } else {
  163. req.Header.Set("X-Stainless-Timeout", strconv.Itoa(int(cfg.RequestTimeout.Seconds())))
  164. }
  165. }
  166. return &cfg, nil
  167. }
  168. func UseDefaultParam[T any](dst *param.Field[T], src *T) {
  169. if !dst.Present && src != nil {
  170. dst.Value = *src
  171. dst.Present = true
  172. }
  173. }
  174. // This interface is primarily used to describe an [*http.Client], but also
  175. // supports custom HTTP implementations.
  176. type HTTPDoer interface {
  177. Do(req *http.Request) (*http.Response, error)
  178. }
  179. // RequestConfig represents all the state related to one request.
  180. //
  181. // Editing the variables inside RequestConfig directly is unstable api. Prefer
  182. // composing the RequestOption instead if possible.
  183. type RequestConfig struct {
  184. MaxRetries int
  185. RequestTimeout time.Duration
  186. Context context.Context
  187. Request *http.Request
  188. BaseURL *url.URL
  189. // DefaultBaseURL will be used if BaseURL is not explicitly overridden using
  190. // WithBaseURL.
  191. DefaultBaseURL *url.URL
  192. CustomHTTPDoer HTTPDoer
  193. HTTPClient *http.Client
  194. Middlewares []middleware
  195. // If ResponseBodyInto not nil, then we will attempt to deserialize into
  196. // ResponseBodyInto. If Destination is a []byte, then it will return the body as
  197. // is.
  198. ResponseBodyInto interface{}
  199. // ResponseInto copies the \*http.Response of the corresponding request into the
  200. // given address
  201. ResponseInto **http.Response
  202. Body io.Reader
  203. }
  204. // middleware is exactly the same type as the Middleware type found in the [option] package,
  205. // but it is redeclared here for circular dependency issues.
  206. type middleware = func(*http.Request, middlewareNext) (*http.Response, error)
  207. // middlewareNext is exactly the same type as the MiddlewareNext type found in the [option] package,
  208. // but it is redeclared here for circular dependency issues.
  209. type middlewareNext = func(*http.Request) (*http.Response, error)
  210. func applyMiddleware(middleware middleware, next middlewareNext) middlewareNext {
  211. return func(req *http.Request) (res *http.Response, err error) {
  212. return middleware(req, next)
  213. }
  214. }
  215. func shouldRetry(req *http.Request, res *http.Response) bool {
  216. // If there is no way to recover the Body, then we shouldn't retry.
  217. if req.Body != nil && req.GetBody == nil {
  218. return false
  219. }
  220. // If there is no response, that indicates that there is a connection error
  221. // so we retry the request.
  222. if res == nil {
  223. return true
  224. }
  225. // If the header explicitly wants a retry behavior, respect that over the
  226. // http status code.
  227. if res.Header.Get("x-should-retry") == "true" {
  228. return true
  229. }
  230. if res.Header.Get("x-should-retry") == "false" {
  231. return false
  232. }
  233. return res.StatusCode == http.StatusRequestTimeout ||
  234. res.StatusCode == http.StatusConflict ||
  235. res.StatusCode == http.StatusTooManyRequests ||
  236. res.StatusCode >= http.StatusInternalServerError
  237. }
  238. func parseRetryAfterHeader(resp *http.Response) (time.Duration, bool) {
  239. if resp == nil {
  240. return 0, false
  241. }
  242. type retryData struct {
  243. header string
  244. units time.Duration
  245. // custom is used when the regular algorithm failed and is optional.
  246. // the returned duration is used verbatim (units is not applied).
  247. custom func(string) (time.Duration, bool)
  248. }
  249. nop := func(string) (time.Duration, bool) { return 0, false }
  250. // the headers are listed in order of preference
  251. retries := []retryData{
  252. {
  253. header: "Retry-After-Ms",
  254. units: time.Millisecond,
  255. custom: nop,
  256. },
  257. {
  258. header: "Retry-After",
  259. units: time.Second,
  260. // retry-after values are expressed in either number of
  261. // seconds or an HTTP-date indicating when to try again
  262. custom: func(ra string) (time.Duration, bool) {
  263. t, err := time.Parse(time.RFC1123, ra)
  264. if err != nil {
  265. return 0, false
  266. }
  267. return time.Until(t), true
  268. },
  269. },
  270. }
  271. for _, retry := range retries {
  272. v := resp.Header.Get(retry.header)
  273. if v == "" {
  274. continue
  275. }
  276. if retryAfter, err := strconv.ParseFloat(v, 64); err == nil {
  277. return time.Duration(retryAfter * float64(retry.units)), true
  278. }
  279. if d, ok := retry.custom(v); ok {
  280. return d, true
  281. }
  282. }
  283. return 0, false
  284. }
  285. // isBeforeContextDeadline reports whether the non-zero Time t is
  286. // before ctx's deadline. If ctx does not have a deadline, it
  287. // always reports true (the deadline is considered infinite).
  288. func isBeforeContextDeadline(t time.Time, ctx context.Context) bool {
  289. d, ok := ctx.Deadline()
  290. if !ok {
  291. return true
  292. }
  293. return t.Before(d)
  294. }
  295. // bodyWithTimeout is an io.ReadCloser which can observe a context's cancel func
  296. // to handle timeouts etc. It wraps an existing io.ReadCloser.
  297. type bodyWithTimeout struct {
  298. stop func() // stops the time.Timer waiting to cancel the request
  299. rc io.ReadCloser
  300. }
  301. func (b *bodyWithTimeout) Read(p []byte) (n int, err error) {
  302. n, err = b.rc.Read(p)
  303. if err == nil {
  304. return n, nil
  305. }
  306. if err == io.EOF {
  307. return n, err
  308. }
  309. return n, err
  310. }
  311. func (b *bodyWithTimeout) Close() error {
  312. err := b.rc.Close()
  313. b.stop()
  314. return err
  315. }
  316. func retryDelay(res *http.Response, retryCount int) time.Duration {
  317. // If the API asks us to wait a certain amount of time (and it's a reasonable amount),
  318. // just do what it says.
  319. if retryAfterDelay, ok := parseRetryAfterHeader(res); ok && 0 <= retryAfterDelay && retryAfterDelay < time.Minute {
  320. return retryAfterDelay
  321. }
  322. maxDelay := 8 * time.Second
  323. delay := time.Duration(0.5 * float64(time.Second) * math.Pow(2, float64(retryCount)))
  324. if delay > maxDelay {
  325. delay = maxDelay
  326. }
  327. jitter := rand.Int63n(int64(delay / 4))
  328. delay -= time.Duration(jitter)
  329. return delay
  330. }
  331. func (cfg *RequestConfig) Execute() (err error) {
  332. if cfg.BaseURL == nil {
  333. if cfg.DefaultBaseURL != nil {
  334. cfg.BaseURL = cfg.DefaultBaseURL
  335. } else {
  336. return fmt.Errorf("requestconfig: base url is not set")
  337. }
  338. }
  339. cfg.Request.URL, err = cfg.BaseURL.Parse(strings.TrimLeft(cfg.Request.URL.String(), "/"))
  340. if err != nil {
  341. return err
  342. }
  343. if cfg.Body != nil && cfg.Request.Body == nil {
  344. switch body := cfg.Body.(type) {
  345. case *bytes.Buffer:
  346. b := body.Bytes()
  347. cfg.Request.ContentLength = int64(body.Len())
  348. cfg.Request.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(b)), nil }
  349. cfg.Request.Body, _ = cfg.Request.GetBody()
  350. case *bytes.Reader:
  351. cfg.Request.ContentLength = int64(body.Len())
  352. cfg.Request.GetBody = func() (io.ReadCloser, error) {
  353. _, err := body.Seek(0, 0)
  354. return io.NopCloser(body), err
  355. }
  356. cfg.Request.Body, _ = cfg.Request.GetBody()
  357. default:
  358. if rc, ok := body.(io.ReadCloser); ok {
  359. cfg.Request.Body = rc
  360. } else {
  361. cfg.Request.Body = io.NopCloser(body)
  362. }
  363. }
  364. }
  365. handler := cfg.HTTPClient.Do
  366. if cfg.CustomHTTPDoer != nil {
  367. handler = cfg.CustomHTTPDoer.Do
  368. }
  369. for i := len(cfg.Middlewares) - 1; i >= 0; i -= 1 {
  370. handler = applyMiddleware(cfg.Middlewares[i], handler)
  371. }
  372. // Don't send the current retry count in the headers if the caller modified the header defaults.
  373. shouldSendRetryCount := cfg.Request.Header.Get("X-Stainless-Retry-Count") == "0"
  374. var res *http.Response
  375. var cancel context.CancelFunc
  376. for retryCount := 0; retryCount <= cfg.MaxRetries; retryCount += 1 {
  377. ctx := cfg.Request.Context()
  378. if cfg.RequestTimeout != time.Duration(0) && isBeforeContextDeadline(time.Now().Add(cfg.RequestTimeout), ctx) {
  379. ctx, cancel = context.WithTimeout(ctx, cfg.RequestTimeout)
  380. defer func() {
  381. // The cancel function is nil if it was handed off to be handled in a different scope.
  382. if cancel != nil {
  383. cancel()
  384. }
  385. }()
  386. }
  387. req := cfg.Request.Clone(ctx)
  388. if shouldSendRetryCount {
  389. req.Header.Set("X-Stainless-Retry-Count", strconv.Itoa(retryCount))
  390. }
  391. res, err = handler(req)
  392. if ctx != nil && ctx.Err() != nil {
  393. return ctx.Err()
  394. }
  395. if !shouldRetry(cfg.Request, res) || retryCount >= cfg.MaxRetries {
  396. break
  397. }
  398. // Prepare next request and wait for the retry delay
  399. if cfg.Request.GetBody != nil {
  400. cfg.Request.Body, err = cfg.Request.GetBody()
  401. if err != nil {
  402. return err
  403. }
  404. }
  405. // Can't actually refresh the body, so we don't attempt to retry here
  406. if cfg.Request.GetBody == nil && cfg.Request.Body != nil {
  407. break
  408. }
  409. time.Sleep(retryDelay(res, retryCount))
  410. }
  411. // Save *http.Response if it is requested to, even if there was an error making the request. This is
  412. // useful in cases where you might want to debug by inspecting the response. Note that if err != nil,
  413. // the response should be generally be empty, but there are edge cases.
  414. if cfg.ResponseInto != nil {
  415. *cfg.ResponseInto = res
  416. }
  417. if responseBodyInto, ok := cfg.ResponseBodyInto.(**http.Response); ok {
  418. *responseBodyInto = res
  419. }
  420. // If there was a connection error in the final request or any other transport error,
  421. // return that early without trying to coerce into an APIError.
  422. if err != nil {
  423. return err
  424. }
  425. if res.StatusCode >= 400 {
  426. contents, err := io.ReadAll(res.Body)
  427. res.Body.Close()
  428. if err != nil {
  429. return err
  430. }
  431. // If there is an APIError, re-populate the response body so that debugging
  432. // utilities can conveniently dump the response without issue.
  433. res.Body = io.NopCloser(bytes.NewBuffer(contents))
  434. // Load the contents into the error format if it is provided.
  435. aerr := apierror.Error{Request: cfg.Request, Response: res, StatusCode: res.StatusCode}
  436. err = aerr.UnmarshalJSON(contents)
  437. if err != nil {
  438. return err
  439. }
  440. return &aerr
  441. }
  442. _, intoCustomResponseBody := cfg.ResponseBodyInto.(**http.Response)
  443. if cfg.ResponseBodyInto == nil || intoCustomResponseBody {
  444. // We aren't reading the response body in this scope, but whoever is will need the
  445. // cancel func from the context to observe request timeouts.
  446. // Put the cancel function in the response body so it can be handled elsewhere.
  447. if cancel != nil {
  448. res.Body = &bodyWithTimeout{rc: res.Body, stop: cancel}
  449. cancel = nil
  450. }
  451. return nil
  452. }
  453. contents, err := io.ReadAll(res.Body)
  454. res.Body.Close()
  455. if err != nil {
  456. return fmt.Errorf("error reading response body: %w", err)
  457. }
  458. // If we are not json, return plaintext
  459. contentType := res.Header.Get("content-type")
  460. mediaType, _, _ := mime.ParseMediaType(contentType)
  461. isJSON := strings.Contains(mediaType, "application/json") || strings.HasSuffix(mediaType, "+json")
  462. if !isJSON {
  463. switch dst := cfg.ResponseBodyInto.(type) {
  464. case *string:
  465. *dst = string(contents)
  466. case **string:
  467. tmp := string(contents)
  468. *dst = &tmp
  469. case *[]byte:
  470. *dst = contents
  471. default:
  472. return fmt.Errorf("expected destination type of 'string' or '[]byte' for responses with content-type '%s' that is not 'application/json'", contentType)
  473. }
  474. return nil
  475. }
  476. switch dst := cfg.ResponseBodyInto.(type) {
  477. // If the response happens to be a byte array, deserialize the body as-is.
  478. case *[]byte:
  479. *dst = contents
  480. default:
  481. err = json.NewDecoder(bytes.NewReader(contents)).Decode(cfg.ResponseBodyInto)
  482. if err != nil {
  483. return fmt.Errorf("error parsing response json: %w", err)
  484. }
  485. }
  486. return nil
  487. }
  488. func ExecuteNewRequest(ctx context.Context, method string, u string, body interface{}, dst interface{}, opts ...RequestOption) error {
  489. cfg, err := NewRequestConfig(ctx, method, u, body, dst, opts...)
  490. if err != nil {
  491. return err
  492. }
  493. return cfg.Execute()
  494. }
  495. func (cfg *RequestConfig) Clone(ctx context.Context) *RequestConfig {
  496. if cfg == nil {
  497. return nil
  498. }
  499. req := cfg.Request.Clone(ctx)
  500. var err error
  501. if req.Body != nil {
  502. req.Body, err = req.GetBody()
  503. }
  504. if err != nil {
  505. return nil
  506. }
  507. new := &RequestConfig{
  508. MaxRetries: cfg.MaxRetries,
  509. RequestTimeout: cfg.RequestTimeout,
  510. Context: ctx,
  511. Request: req,
  512. BaseURL: cfg.BaseURL,
  513. HTTPClient: cfg.HTTPClient,
  514. Middlewares: cfg.Middlewares,
  515. }
  516. return new
  517. }
  518. func (cfg *RequestConfig) Apply(opts ...RequestOption) error {
  519. for _, opt := range opts {
  520. err := opt.Apply(cfg)
  521. if err != nil {
  522. return err
  523. }
  524. }
  525. return nil
  526. }
  527. // PreRequestOptions is used to collect all the options which need to be known before
  528. // a call to [RequestConfig.ExecuteNewRequest], such as path parameters
  529. // or global defaults.
  530. // PreRequestOptions will return a [RequestConfig] with the options applied.
  531. //
  532. // Only request option functions of type [PreRequestOptionFunc] are applied.
  533. func PreRequestOptions(opts ...RequestOption) (RequestConfig, error) {
  534. cfg := RequestConfig{}
  535. for _, opt := range opts {
  536. if opt, ok := opt.(PreRequestOptionFunc); ok {
  537. err := opt.Apply(&cfg)
  538. if err != nil {
  539. return cfg, err
  540. }
  541. }
  542. }
  543. return cfg, nil
  544. }
  545. // WithDefaultBaseURL returns a RequestOption that sets the client's default Base URL.
  546. // This is always overridden by setting a base URL with WithBaseURL.
  547. // WithBaseURL should be used instead of WithDefaultBaseURL except in internal code.
  548. func WithDefaultBaseURL(baseURL string) RequestOption {
  549. u, err := url.Parse(baseURL)
  550. return RequestOptionFunc(func(r *RequestConfig) error {
  551. if err != nil {
  552. return err
  553. }
  554. r.DefaultBaseURL = u
  555. return nil
  556. })
  557. }