requestconfig.go 17 KB

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