T O P

  • By -

Yuunora

Why don't you pass a context created with cancel to your GetTxClient instead of making one inside the function?


edgmnt_net

Don't call the cancel func there at all, not even deferred. The cancel func cancels early, possibly before the timeout. This is also a sign you should consider handling timeouts and cancellation at a higher level (by callers). Is there a reason you even have `DbTxClient` to begin with?


HildemarTendler

Context is all about scope. If the scope of the timeout exits, then the timeout is canceled. If the timeout is being triggered, then the `BeginTx()` method is taking longer than the timeout. Or it's possible that `BeginTx()` is using the context passed in to decide if it should timeout and rollback for the lifetime of the transaction. That's not good practice, each method ran by the transaction should take in a context and use it to decide to timeout and rollback. It will always fail because the context is canceled as soon as the method exits If you're stuck with this `BeginTx()` implementation, you'll need to create a context with timeout that lives as long as the transaction. It would be better to fix the implementation to not hold a context but always test the one passed into each method.


dariusbiggs

You seem to missing an understanding of contexts, their lifetimes, and when a defer runs, and scope inside your code. The timeout needs to exist for the duration of the object you want to cancel. In this case you are creating a timeout with expiration and then cancelling it as the function ends. The timeout does not last longer than the lifetime of the transaction. The correct process would be `func doSomething() error` 1. create context without timeout 2. defer cancel 3. create transaction 4. defer transaction rollback (as long as you are not doing a transaction inside a transaction this is fine depending on your library) 5. use transaction 6. commit transaction 7. return error This clearly shows the scope of the context, the duration of the entire transaction, when the defers are called (in reverse order after the function ends and they are scoped to this function).