Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## Unreleased

### Fixed

- Fix the streaming producer's unary RPC client crash-looping on exactly-once
subscriptions. Pub/Sub rejects expired or invalid ack ids with
`INVALID_ARGUMENT` and lists them in an `ErrorInfo` detail; that status was
treated as terminal, so the client stopped, and `AckBatcher` sent the same
batch to the restarted client, which stopped again, until the ack retry
deadline. A terminal status with per-ack-id details is now handled like a
retryable one: the permanently failed ids are counted on
`[:broadway_cloud_pub_sub, :streaming, :unary, :permanent_failure]` and the
client keeps running, without logging. Only an `ErrorInfo` with
reason `EXACTLY_ONCE_ACKID_FAILURE` counts as per-ack-id details, so other
terminal errors, such as `PERMISSION_DENIED`, still stop the client.

## [2.1.0]

### Added
Expand Down
6 changes: 4 additions & 2 deletions lib/broadway_cloud_pub_sub/producer.ex
Original file line number Diff line number Diff line change
Expand Up @@ -376,8 +376,10 @@ defmodule BroadwayCloudPubSub.Producer do
Metadata includes: `reason: term()` - the connection error.

* `[:broadway_cloud_pub_sub, :streaming, :unary, :permanent_failure]` -
one or more ack_ids were permanently rejected by the server (e.g. ack_id
expired). These are dropped and not retried.
one or more ack_ids in an Acknowledge or ModifyAckDeadline request were
permanently rejected by the server (e.g. ack_id expired). The count is
per rejected request, not per unique ack_id: the ids may be sent again
until the ack retry deadline, and each rejection is counted.

Measurements: `%{count: pos_integer()}`

Expand Down
23 changes: 17 additions & 6 deletions lib/broadway_cloud_pub_sub/streaming/ack_result.ex
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,17 @@ defmodule BroadwayCloudPubSub.Streaming.AckResult do
# when an Acknowledge or ModifyAckDeadline RPC partially fails. The errors are
# encoded in a `google.rpc.Status` detail of type `google.rpc.ErrorInfo`:
#
# - `reason` field: either "TRANSIENT_<details>" (retry) or "PERMANENT_<details>"
# - `metadata` map: keys are ack_ids, values are the per-ack-id error reason
# - `reason` field: "EXACTLY_ONCE_ACKID_FAILURE"
# - `metadata` map: keys are ack_ids, values are the per-ack-id error reason,
# either "TRANSIENT_<details>" (retry) or "PERMANENT_<details>"
#
# Transient errors should be retried; permanent errors indicate an invalid ack ID
# and should be resolved immediately with the appropriate status.
#
# An ErrorInfo with any other reason is a general error detail (for example
# "IAM_PERMISSION_DENIED" with a "permission" key in its metadata), not a
# per-ack-ID answer, and is ignored.
#
# ## Status values
#
# | Status | Meaning |
Expand All @@ -53,6 +58,9 @@ defmodule BroadwayCloudPubSub.Streaming.AckResult do

defstruct [:ack_id, :status, :error]

# The ErrorInfo reason Pub/Sub uses for per-ack-ID answers.
@ack_id_failure_reason "EXACTLY_ONCE_ACKID_FAILURE"

@doc """
Returns a successful AckResult for the given ack_id.
"""
Expand All @@ -70,9 +78,11 @@ defmodule BroadwayCloudPubSub.Streaming.AckResult do
Parses per-ack-ID error information from a `GRPC.RPCError`'s details list.

Google's Pub/Sub API encodes per-ack-ID errors in `google.rpc.ErrorInfo` details
when an Acknowledge or ModifyAckDeadline RPC partially fails. The `metadata` map
in `ErrorInfo` maps ack_id => error_reason, where the reason has either a
"TRANSIENT_" or "PERMANENT_" prefix.
when an Acknowledge or ModifyAckDeadline RPC partially fails. Only an
`ErrorInfo` whose reason is "EXACTLY_ONCE_ACKID_FAILURE" carries them: its
`metadata` map maps ack_id => error_reason, where the reason has either a
"TRANSIENT_" or "PERMANENT_" prefix. `ErrorInfo` details with any other reason
are ignored.

Returns a map of `ack_id => :transient | {:permanent, reason_string}`.

Expand All @@ -87,7 +97,8 @@ defmodule BroadwayCloudPubSub.Streaming.AckResult do
def parse_error_details(details) when is_list(details) do
Enum.reduce(details, %{}, fn any_proto, acc ->
case decode_error_info(any_proto) do
{:ok, %Google.Rpc.ErrorInfo{metadata: metadata}} when map_size(metadata) > 0 ->
{:ok, %Google.Rpc.ErrorInfo{reason: @ack_id_failure_reason, metadata: metadata}}
when map_size(metadata) > 0 ->
Enum.reduce(metadata, acc, fn {ack_id, reason}, inner_acc ->
Map.put(inner_acc, ack_id, classify_reason(reason))
end)
Expand Down
43 changes: 36 additions & 7 deletions lib/broadway_cloud_pub_sub/streaming/unary_rpc_client.ex
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ defmodule BroadwayCloudPubSub.Streaming.UnaryRpcClient do
# - Terminal error → stop the GenServer via {:stop, reason, reply, state} so the
# supervisor restarts it fresh. The caller receives {:error, reason}
# first (from the reply in the stop tuple) so it can retain ack_ids.
# Exception: a terminal status that carries per-ack-id details
# (an exactly-once ErrorInfo, see AckResult) is handled like a
# retryable error, without the reconnect, and the GenServer keeps
# running.
#
# Retry timing and back-pressure belong to the caller (AckBatcher), not here.
#
Expand Down Expand Up @@ -294,21 +298,32 @@ defmodule BroadwayCloudPubSub.Streaming.UnaryRpcClient do
end

defp handle_rpc_error(state, ack_ids, error, operation) do
per_ack_errors = AckResult.parse_error_details(error_details(error))

case ErrorClassifier.classify(error) do
:retryable ->
# For exactly-once subscriptions, retryable RPC errors may embed
# per-ack-ID permanent failures in error details. Permanent ids
# are dropped; transient ones are returned to AckBatcher for retry.
per_ack_errors = AckResult.parse_error_details(error_details(error))
{transient_ids, permanent_ids} = split_by_ack_result(ack_ids, per_ack_errors)

if permanent_ids != [] do
emit_telemetry(:permanent_failure, %{count: length(permanent_ids)}, state.config)
end

transient_ids = drop_permanent_failures(state, ack_ids, per_ack_errors)
state = schedule_reconnect(state)
{:reply, {:error, {error, transient_ids}}, state}

# For exactly-once subscriptions, Pub/Sub rejects expired or otherwise
# invalid ack ids with INVALID_ARGUMENT and lists them per ack id in an
# ErrorInfo detail. The status code is terminal, but the call reached
# the server and was answered per ack id, so handle it like a retryable
# error with per-ack-id details instead of stopping. Stopping made
# AckBatcher resend the same batch to a fresh process, which got the
# same answer and stopped again, every flush until the ack retry
# deadline. AckResult decides which details are per-ack-id answers, so
# other terminal errors (e.g. PERMISSION_DENIED with a general ErrorInfo)
# still stop the client below.
# The rejected ids are reported through telemetry only, not logged.
:terminal when per_ack_errors != %{} ->
transient_ids = drop_permanent_failures(state, ack_ids, per_ack_errors)
{:reply, {:error, {error, transient_ids}}, state}

:terminal ->
Logger.error(
"Unable to #{operation} with Cloud Pub/Sub via gRPC - reason: #{inspect(error)}"
Expand Down Expand Up @@ -366,6 +381,20 @@ defmodule BroadwayCloudPubSub.Streaming.UnaryRpcClient do
defp error_details(%{details: details}), do: details
defp error_details(_), do: nil

# Counts the ack ids Pub/Sub rejected for good on :permanent_failure and
# returns the rest for retry. The count is per rejected attempt: while
# chunked_rpc/3 hands the whole failed chunk back to AckBatcher, the same
# permanent ids are resent and counted again until the ack retry deadline.
defp drop_permanent_failures(state, ack_ids, per_ack_errors) do
{transient_ids, permanent_ids} = split_by_ack_result(ack_ids, per_ack_errors)

if permanent_ids != [] do
emit_telemetry(:permanent_failure, %{count: length(permanent_ids)}, state.config)
end

transient_ids
end

# Splits ack_ids into {transient, permanent} based on per-ack-ID error details
# parsed from the gRPC error. If there are no per-ack-ID details (the common
# case), all ids are treated as transient so the caller retries them all.
Expand Down
30 changes: 21 additions & 9 deletions test/broadway_cloud_pub_sub/streaming/ack_result_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ defmodule BroadwayCloudPubSub.Streaming.AckResultTest do
describe "parse_error_details/1 — transient per-ack-id errors" do
test "returns :transient for ack_ids with TRANSIENT_ reason" do
error_info = %Google.Rpc.ErrorInfo{
reason: "TRANSIENT_FAILURE_INVALID_ACK_ID",
reason: "EXACTLY_ONCE_ACKID_FAILURE",
domain: "pubsub.googleapis.com",
metadata: %{
"ack-1" => "TRANSIENT_FAILURE_INVALID_ACK_ID",
Expand All @@ -101,7 +101,7 @@ defmodule BroadwayCloudPubSub.Streaming.AckResultTest do

test "returns :transient for all TRANSIENT_ variants" do
error_info = %Google.Rpc.ErrorInfo{
reason: "TRANSIENT_SOMETHING",
reason: "EXACTLY_ONCE_ACKID_FAILURE",
domain: "pubsub.googleapis.com",
metadata: %{"ack-x" => "TRANSIENT_SOMETHING"}
}
Expand All @@ -116,7 +116,7 @@ defmodule BroadwayCloudPubSub.Streaming.AckResultTest do
describe "parse_error_details/1 — permanent per-ack-id errors" do
test "returns {:permanent, reason} for ack_ids with PERMANENT_ reason" do
error_info = %Google.Rpc.ErrorInfo{
reason: "PERMANENT_FAILURE_INVALID_ACK_ID",
reason: "EXACTLY_ONCE_ACKID_FAILURE",
domain: "pubsub.googleapis.com",
metadata: %{"ack-3" => "PERMANENT_FAILURE_INVALID_ACK_ID"}
}
Expand All @@ -129,7 +129,7 @@ defmodule BroadwayCloudPubSub.Streaming.AckResultTest do

test "returns {:permanent, reason} for unrecognised (non-TRANSIENT_) reason" do
error_info = %Google.Rpc.ErrorInfo{
reason: "SOMETHING_COMPLETELY_DIFFERENT",
reason: "EXACTLY_ONCE_ACKID_FAILURE",
domain: "pubsub.googleapis.com",
metadata: %{"ack-4" => "SOMETHING_COMPLETELY_DIFFERENT"}
}
Expand All @@ -144,7 +144,7 @@ defmodule BroadwayCloudPubSub.Streaming.AckResultTest do
describe "parse_error_details/1 — mixed transient and permanent" do
test "correctly classifies each ack_id independently" do
error_info = %Google.Rpc.ErrorInfo{
reason: "MIXED",
reason: "EXACTLY_ONCE_ACKID_FAILURE",
domain: "pubsub.googleapis.com",
metadata: %{
"ack-transient" => "TRANSIENT_FAILURE_INVALID_ACK_ID",
Expand All @@ -163,13 +163,13 @@ defmodule BroadwayCloudPubSub.Streaming.AckResultTest do
describe "parse_error_details/1 — multiple Any details" do
test "merges results from multiple ErrorInfo entries" do
error_info_1 = %Google.Rpc.ErrorInfo{
reason: "TRANSIENT_FAILURE_INVALID_ACK_ID",
reason: "EXACTLY_ONCE_ACKID_FAILURE",
domain: "pubsub.googleapis.com",
metadata: %{"ack-a" => "TRANSIENT_FAILURE_INVALID_ACK_ID"}
}

error_info_2 = %Google.Rpc.ErrorInfo{
reason: "PERMANENT_FAILURE_INVALID_ACK_ID",
reason: "EXACTLY_ONCE_ACKID_FAILURE",
domain: "pubsub.googleapis.com",
metadata: %{"ack-b" => "PERMANENT_FAILURE_INVALID_ACK_ID"}
}
Expand All @@ -187,7 +187,7 @@ defmodule BroadwayCloudPubSub.Streaming.AckResultTest do

test "skips non-ErrorInfo entries between valid ones" do
error_info = %Google.Rpc.ErrorInfo{
reason: "TRANSIENT_FAILURE",
reason: "EXACTLY_ONCE_ACKID_FAILURE",
domain: "pubsub.googleapis.com",
metadata: %{"ack-z" => "TRANSIENT_FAILURE"}
}
Expand All @@ -202,10 +202,22 @@ defmodule BroadwayCloudPubSub.Streaming.AckResultTest do
end
end

describe "parse_error_details/1: ErrorInfo with another reason" do
test "ignores an ErrorInfo that is not an EXACTLY_ONCE_ACKID_FAILURE" do
error_info = %Google.Rpc.ErrorInfo{
reason: "IAM_PERMISSION_DENIED",
domain: "pubsub.googleapis.com",
metadata: %{"permission" => "pubsub.subscriptions.consume"}
}

assert AckResult.parse_error_details([build_error_info_any(error_info)]) == %{}
end
end

describe "parse_error_details/1 — empty metadata" do
test "returns empty map when ErrorInfo metadata is empty" do
error_info = %Google.Rpc.ErrorInfo{
reason: "SOME_ERROR",
reason: "EXACTLY_ONCE_ACKID_FAILURE",
domain: "pubsub.googleapis.com",
metadata: %{}
}
Expand Down
116 changes: 116 additions & 0 deletions test/broadway_cloud_pub_sub/streaming/unary_rpc_client_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -676,5 +676,121 @@ defmodule BroadwayCloudPubSub.Streaming.UnaryRpcClientTest do

Process.flag(:trap_exit, false)
end

# Exactly-once subscriptions reject expired or invalid ack ids with
# INVALID_ARGUMENT and an ErrorInfo detail listing them. The status is
# terminal, but stopping on it made the client crash-loop on every resend
# of the batch until the ack retry deadline.
test "terminal status with per-ack-id ErrorInfo counts permanent ids and keeps running" do
test_pid = self()
telemetry_name = "unary-eod-permanent-#{System.unique_integer([:positive])}"

:telemetry.attach(
telemetry_name,
[:broadway_cloud_pub_sub, :streaming, :unary, :permanent_failure],
&TelemetryHelper.handle_event_forward_test/4,
%{pid: test_pid, msg: :permanent_failure}
)

on_exit(fn -> :telemetry.detach(telemetry_name) end)

error_info = %Google.Rpc.ErrorInfo{
reason: "EXACTLY_ONCE_ACKID_FAILURE",
domain: "pubsub.googleapis.com",
metadata: %{
"ack-expired" => "PERMANENT_FAILURE_INVALID_ACK_ID",
"ack-transient" => "TRANSIENT_FAILURE_UNORDERED_ACK_ID"
}
}

error = %GRPC.RPCError{
status: GRPC.Status.invalid_argument(),
message: "Some acknowledgement ids in the request were invalid.",
details: [
%Google.Protobuf.Any{
type_url: "type.googleapis.com/google.rpc.ErrorInfo",
value: Google.Rpc.ErrorInfo.encode(error_info)
}
]
}

pid = start_client_with_failing_rpc(error)
assert_receive {:fake_grpc, :connect, _conn_pid}
ref = Process.monitor(pid)

ack_ids = ["ack-expired", "ack-transient", "ack-unlisted"]

# Which ids come back for retry is not asserted here: today the whole
# failed chunk is handed back to AckBatcher, including "ack-expired",
# which is a known limitation rather than intended behavior.
log =
capture_log(fn ->
assert {:ok, retained} = UnaryRpcClient.acknowledge(pid, ack_ids)
assert "ack-transient" in retained
assert "ack-unlisted" in retained
end)

# Reported through telemetry only: the library does not log it.
assert log == ""

assert_receive {:permanent_failure, %{count: 1}, %{subscription: _}}, 1_000
refute_received {:DOWN, ^ref, :process, ^pid, _reason}
assert Process.alive?(pid)
end

@tag capture_log: true
test "terminal status without per-ack-id details still stops the GenServer" do
error = %GRPC.RPCError{
status: GRPC.Status.invalid_argument(),
message: "bad request",
details: []
}

pid = start_client_with_failing_rpc(error)
assert_receive {:fake_grpc, :connect, _conn_pid}
ref = Process.monitor(pid)
Process.flag(:trap_exit, true)

capture_log(fn ->
assert {:ok, ["ack-1"]} = UnaryRpcClient.acknowledge(pid, ["ack-1"])
assert_receive {:DOWN, ^ref, :process, ^pid, {:terminal_error, ^error}}
end)

Process.flag(:trap_exit, false)
end

# A general ErrorInfo (not EXACTLY_ONCE_ACKID_FAILURE) is not a per-ack-id
# answer, so a terminal status carrying one must still stop the client.
@tag capture_log: true
test "terminal status with a general ErrorInfo still stops the GenServer" do
error_info = %Google.Rpc.ErrorInfo{
reason: "IAM_PERMISSION_DENIED",
domain: "pubsub.googleapis.com",
metadata: %{"permission" => "pubsub.subscriptions.consume"}
}

error = %GRPC.RPCError{
status: GRPC.Status.permission_denied(),
message: "permission denied",
details: [
%Google.Protobuf.Any{
type_url: "type.googleapis.com/google.rpc.ErrorInfo",
value: Google.Rpc.ErrorInfo.encode(error_info)
}
]
}

pid = start_client_with_failing_rpc(error)
assert_receive {:fake_grpc, :connect, _conn_pid}
ref = Process.monitor(pid)
Process.flag(:trap_exit, true)

capture_log(fn ->
assert {:ok, ["ack-1"]} = UnaryRpcClient.acknowledge(pid, ["ack-1"])
assert_receive {:DOWN, ^ref, :process, ^pid, {:terminal_error, ^error}}
end)

Process.flag(:trap_exit, false)
end
end
end