Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

stripe-go v71 #1055

Merged
merged 11 commits into from
Apr 17, 2020
Merged

stripe-go v71 #1055

merged 11 commits into from
Apr 17, 2020

Conversation

brandur
Copy link
Contributor

@brandur brandur commented Apr 1, 2020

Integration branch for the next major version of stripe-go.

⚠️ = breaking change

* Make API response accessible on returned API structs

Makes an API response struct containing niceties like the raw response
body, status, and request ID accessible via API resource structs
returned from client functions. For example:

    customer, err := customer.New(params)
    fmt.Printf("request ID = %s\n", customer.LastResponse.RequestID)

This is a feature that already exists in other language API libraries
and which is requested occasionally here, usually for various situations
involving more complex usage or desire for better observability.

-- Implementation

We introduce a few new types to make this work:

* `APIResponse`: Represents a response from the Stripe API and includes
  things like request ID, status, and headers. I elected to create my
  own object instead of reusing `http.Response` because it gives us a
  little more flexibility, and hides many of myriad of fields exposed by
  the `http` version, which will hopefully give us a little more API
  stability/forward compatibility.

* `APIResource`: A struct that contains `LastResponse` and is meant to
  represent any type that can we returned from a Stripe API endpoint. A
  coupon is an `APIResource` and so is a list object. This struct is
  embedded in response structs where appropriate across the whole API
  surface area (e.g. `Coupon`, `ListMeta`, etc.).

* `LastResponseGetter`: A very basic interface to an object that looks
  like an `APIResource`. This isn't strictly necessary, but gives us
  slightly more flexibility around the API and makes backward
  compatibility a little bit better for non-standard use cases (see the
  section on that below).

`stripe.Do` and other backend calls all start taking objects which are
`LastResponseGetter` instead of `interface{}`. This provides us with some
type safety around forgetting to include an embedded `APIResource` on
structs that should have it by making the compiler balk.

As `stripe.Do` finishes running a request, it generates an `APIResponse`
object and sets it onto the API resource type it's deserializing and
returning (e.g. a `Coupon`).

Errors also embed `APIResource` and similarly get access to the same set
of fields as response resources, although in their case some of the
fields provided in `APIResponse` are duplicates of what they had
already (see "Caveats" below).

-- Backwards compatibility

This is a minor breaking change in that backend implementations methods
like `Do` now take `LastResponseGetter` instead of `interface{}`, which
is more strict.

The good news though is that:

* Very few users should be using any of these even if they're
  technically public. The resource-specific clients packages tend to do
  all the work.

* Users who are broken should have a very easy time updating code.
  Mostly this will just involve adding `APIResource` to structs that were
  being passed in.

-- Naming

* `APIResponse`: Went with this instead of `StripeResponse` as we see in
  some other libraries because the linter will complain that it
  "stutters" when used outside of the package (meaning, uses the same
  word twice in a row), i.e. `stripe.StripeResponse`. `APIResponse`
  sorts nicely with `APIResource` though, so I think it's okay.

* `LastResponse`: Copied the "last" convention from other API libraries
  like stripe-python.

* `LastResponseGetter`: Given an "-er" name per Go convention around
  small interfaces that are basically one liners -- e.g. `Reader`,
  `Writer, `Formatter`, `CloseNotifier`, etc. I can see the argument
  that this maybe should just be `APIResourceInterface` or something
  like that in case we start adding new things, but I figure at that
  point we can either rename it, or create a parent interface that
  encapsulates it:

    ``` go
    type APIResourceInterface interface {
        LastResponseGetter
    }
    ```

-- Caveats

* We only set the last response for top-level returned objects. For
  example, an `InvoiceItem` is an API resource, but if it's returned
  under an `Invoice`, only `Invoice` has a non-nil `LastResponse`. The
  same applies for all resources under list objects. I figure that doing
  it this way is more performant and makes a little bit more intuitive
  sense. Users should be able to work around it if they need to.

* There is some duplication between `LastResponse` and some other fields
  that already existed on `stripe.Error` because the latter was already
  exposing some of this information, e.g. `RequestID`. I figure this is
  okay: it's nice that `stripe.Error` is a `LastResponseGetter` for
  consistency with other API resources. The duplication is a little
  unfortunate, but not that big of a deal.

* Rename `LastResponseGetter` to `LastResponseSetter` and remove a function

* Update stripe.go

Co-Authored-By: Olivier Bellone <ob@stripe.com>

* Move `APIResource` onto individual list structs instead of having it in `ListMeta`

Co-authored-by: Brandur <brandur@stripe.com>
Co-authored-by: Olivier Bellone <ob@stripe.com>
remi-stripe and others added 7 commits April 16, 2020 11:07
* `PaymentIntent` is now expandable on `Charge`
* `Percentage` was removed as a filter when listing `TaxRate`
* Removed `RenewalInterval` on `SubscriptionSchedule`
* Removed `Country` and `RoutingNumber` from `ChargePaymentMethodDetailsAcssDebit`
Remove all beta features from Issuing APIs
Similar to the original implementation for Go Modules in #712, here we
add a `go.mod` and `go.sum`, then proceed to use Go Modules style
import paths everywhere that include the current major revision.

Unfortunately, this may still cause trouble for Dep users who are trying
to upgrade stripe-go, but the project's now had two years to help its
users with basic Go Module awareness, and has chosen not to do so. It's
received no commits of any kind since August 2019, and therefore would
be considered unmaintained by most definitions. Elsewhere, Go Modules
now seem to be the only and obvious way forward, so we're likely to see
more and more users on them.

`scripts/check_api_clients/main.go` is also updated to be smarter about
breaking down package paths which may now include the major.

[1] golang/dep#1963
Move back down to current major version so that we can test that our
release script will bump it to v71 properly when the time comes.
## Background

For a very long time, stripe-go logged by way of the `Printfer`
interface:

``` go
type Printfer interface {
       Printf(format string, v ...interface{})
}
```

`Printfer` had a few problems: it didn't allow any kind of granularity
around logging levels, didn't allow us to behave well by sending errors
to `stderr` and other output to `stdout`, and wasn't interoperable with
any popular Go loggers (it was interoperable with the one in the
stdlib's `log`, but serious programs tend to move away from that).

A while back, I introduced the new `LeveledLogger` interface, which
corrected the deficiencies with `Printfer`.

We made quite a bit of effort to stay compatible with the existing
configuration options around logging like the `Logger` and `LogLevel`
globals, while also adding new ones for the leveled logger like
`DefaultLeveledLogger`.

The downside of that is it made reasoning about the different
combinations complicated. For example, you had to know that if both
`Logger` and `DefaultLeveledLogger` were set, then the former would take
precedence, which isn't necessarily obvious.

 ## Changes in this patch

Since we're on the verge of a major, I've taken the liberty of cleaning
up all the old logging infrastructure. This involves removing its types,
interfaces, helpers, global configuration options, and local
configuration options. We're left with a much simpler setup with just
`stripe.DefaultLeveledLogger` and `BackendConfig.LeveledLogger`.

Users who were already using the leveled logger (as recommended in the
README for sometime) won't have to change anything, nor will users who
had no logging configured. Users on the old infrastructure will have to
make some config tweaks, but ones that are quite easy.

And since we're changing logging things anyway: I've made a small tweak
such that if left unset by the user, the default logger now logs errors
only (instead of errors + informational). This is a more reasonable
default on Unix systems where programs are generally not expected to be
noisy over stdout. If a user wants to get informational messages back,
it's a very easy configuration tweak to `DefaultLeveledLogger`.
Currently, it's possible to have the library retry intermittently failed
requests by configuring `MaxNetworkRetries` on a `BackendConfig`.
Because this is a pretty useful feature that many users will never
discover because it's off by default, we've been mulling around the idea
internally to change that default on the next major so that more people
get access to it. We're about to release V71, so now is an opportune
moment.

The slight complication is that `BackendConfig.MaxNetworkRetries` is
currently a simple `int`, which means that it's hard for us to recognize
an unset value versus an explicitly set 0 (the same problem we had with
fields on parameter structs for years). So by example, this code is
problematic:

``` go
if conf.MaxNetworkRetries == 0 {
    backend.MaxNetworkRetries = 2
}
```

The most obvious solution is that change `MaxNetworkRetries` to a
nilable pointer, and have it set using our `stripe.Int64` helper,
exactly as we do for parameter structs. So compared to today,
configuring it would change like this:

``` patch
 config := &stripe.BackendConfig{
-    MaxNetworkRetries: 2,
+    MaxNetworkRetries: stripe.Int64(2),
 }
```

It's not too bad, and follows convention found elsewhere in the library,
but will require a small code update for users.

The slight follow on complication is that to make `BackendConfig`
self-consistent, I also changed the other primitives on it to also be
pointers, so `EnableTelemetry` changes from `bool` to `*bool` and `URL`
changes from `string` to `*string`. I don't think this is a big deal
because ~99% of users will probably just be using the defaults by having
left them unset.
@brandur brandur mentioned this pull request Apr 17, 2020
V71 has a few non-trivial breaking changes bundled in, so add a guide
with more lengthy explanations on how to handle each one (as we've done
previously on occasion like for the big V32 major).
@brandur-stripe brandur-stripe merged commit d5e092a into master Apr 17, 2020
@brandur-stripe brandur-stripe deleted the integration-v71 branch April 17, 2020 20:18
@brandur-stripe
Copy link
Contributor

Released as 71.0.0!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants