Submit a Bulk Feed and Follow It
Register a company's card program as a network bulk feed, handle the networkbulkfeed.statechanged webhook in your worker, and count the card subscriptions the feed made.
For: developers
With network bulk enrollment, the card network sends Astrada a company's cards on a schedule. You register the company's card program as a network bulk feed on a subaccount. The feed starts submitted, and Astrada sends a networkbulkfeed.statechanged webhook when it moves on, for example from submitted to active. This recipe submits the feed, handles that webhook in your worker, and reads the results.
| State | What it means |
|---|---|
submitted | Registered; no cards have arrived yet |
active | Cards have arrived from the network |
failed | Visa only: the feed could not be set up, and errorReason says why |
deactivated | The feed was turned off later |
Before you start
- Scopes:
network-bulk-feeds:writeto submit,network-bulk-feeds:read, andcard-subscriptions:read. - The company's reference at its card network. Network Bulk Enrollment says which reference each network uses and how the company gets it.
- Your receiver from recipe 1, and
networkbulkfeed.statechangedadded to the event types of the subaccount's webhook (recipe 2). - Sandbox or production. In the sandbox, play the network with the bulk feed simulation: Send a simulated delivery. The recipe itself uses only calls that also work in production.
The code
Submit the feed
Submitting again is safe. If the subaccount already has a feed for that network reference that has not failed, Astrada answers 409 ("The network bulk feed already exists") and the code finds that feed and uses it. If the code finds no such feed on the subaccount, it raises the error for a person to look at.
The SDK sends an Idempotency-Key with the create and retries under that key, so do not wrap the call in a retry loop of your own. If a 409 comes back with the code IDEMPOTENCY_KEY_IN_FLIGHT, the first attempt may still be running, so the code raises it for you to try again a little later.
/** Creates the feed, or finds the one that exists already (409). */
export async function submitBulkFeed(
astrada: Astrada,
params: NetworkBulkFeedCreateParams,
): Promise<{ feed: NetworkBulkFeeds; created: boolean }> {
try {
return { feed: await astrada.networkBulkFeeds.create(params), created: true };
} catch (error) {
if (!(error instanceof ConflictError)) throw error;
// Still running after the SDK's retries: not a duplicate feed. Try again later.
if (error.code === IDEMPOTENCY_KEY_IN_FLIGHT) throw error;
// 409: a feed for this network reference exists. Use it when it is on this subaccount.
for await (const feed of astrada.networkBulkFeeds.listAll({
networkReference: params.networkReference,
subaccountId: params.subaccountId,
})) {
if (feed.network === params.network) return { feed, created: false };
}
throw error; // it exists, but not on this subaccount: a person needs to look
}
}def submit_bulk_feed(client: astrada.Astrada, params: Mapping[str, Any]) -> Tuple[astrada.NetworkBulkFeeds, bool]:
"""Creates the feed, or finds the one that exists already (409). Returns (feed, created)."""
try:
return client.network_bulk_feeds.create(params), True
except astrada.IdempotencyKeyInFlightError:
raise # still running after the SDK's retries: not a duplicate feed. Try again later.
except astrada.ConflictError:
# 409: a feed for this network reference exists. Use it when it is on this subaccount.
for feed in client.network_bulk_feeds.list_all(network_reference=params["networkReference"],
subaccount_id=params["subaccountId"]):
if feed.network == params["network"]:
return feed, False
raise # it exists, but not on this subaccount: a person needs to look/** The feed, and whether this call created it. */
public static final class Submitted {
public final NetworkBulkFeeds feed;
public final boolean created;
Submitted(NetworkBulkFeeds feed, boolean created) {
this.feed = feed;
this.created = created;
}
}
/**
* Creates the feed, or finds the one that exists already (409). {@code type} is the rail
* (VCF or VBDS for Visa; null lets Astrada find it), and is left out for the other networks.
*/
public static Submitted submitBulkFeed(ApiClient client, String network, String type, String networkReference,
UUID subaccountId) {
try {
NetworkBulkFeeds feed;
switch (network) {
case "VISA":
feed = client.networkBulkFeeds().create(new NetworkBulkFeedCreateVisa()
.network(NetworkBulkFeedCreateVisa.NetworkEnum.VISA)
.type(type == null ? null : NetworkBulkFeedCreateVisa.TypeEnum.fromValue(type))
.networkReference(networkReference).subaccountId(subaccountId));
break;
case "MASTERCARD":
feed = client.networkBulkFeeds().create(new NetworkBulkFeedCreateMastercard()
.network(NetworkBulkFeedCreateMastercard.NetworkEnum.MASTERCARD)
.networkReference(networkReference).subaccountId(subaccountId));
break;
case "AMEX":
feed = client.networkBulkFeeds().create(new NetworkBulkFeedCreateAmex()
.network(NetworkBulkFeedCreateAmex.NetworkEnum.AMEX)
.networkReference(networkReference).subaccountId(subaccountId));
break;
default:
throw new IllegalArgumentException("network must be VISA, MASTERCARD or AMEX");
}
return new Submitted(feed, true);
} catch (ConflictException e) {
if ("IDEMPOTENCY_KEY_IN_FLIGHT".equals(e.getCode())) {
throw e; // still running after the SDK's retries: not a duplicate feed. Try again later.
}
// 409: a feed for this network reference exists. Use it when it is on this subaccount.
for (NetworkBulkFeeds feed : client.networkBulkFeeds().listAll(ListNetworkBulkFeedsRequest.builder()
.networkReference(networkReference).subaccountId(subaccountId).build())) {
if (network.equals(feed.getNetworkRawValue())) {
return new Submitted(feed, false);
}
}
throw e; // it exists, but not on this subaccount: a person needs to look
}
}Read the results
The webhook says what changed, and a later webhook may have moved the feed on since, so the code reads the feed as it is now, and counts the card subscriptions the feed made by their state.
/** What a feed has done so far. */
export interface FeedResults {
feedId: string;
state: string;
type: string | null;
/** Why it failed, when `state` is `failed` (Visa only). */
errorReason: string | null;
/** The card subscriptions the feed made, counted by their state. */
subscriptionsByState: Record<string, number>;
}@dataclass
class FeedResults:
"""What a feed has done so far."""
feed_id: str
state: str
type: Optional[str]
# Why it failed, when `state` is `failed` (Visa only).
error_reason: Optional[str]
# The card subscriptions the feed made, counted by their state.
subscriptions_by_state: Dict[str, int] = field(default_factory=dict)/** What a feed has done so far. */
public static final class FeedResults {
public final UUID feedId;
public final String state;
public final String type;
/** Why it failed, when {@code state} is {@code failed} (Visa only). */
public final String errorReason;
/** The card subscriptions the feed made, counted by their state. */
public final Map<String, Integer> subscriptionsByState;
FeedResults(UUID feedId, String state, String type, String errorReason, Map<String, Integer> subscriptionsByState) {
this.feedId = feedId;
this.state = state;
this.type = type;
this.errorReason = errorReason;
this.subscriptionsByState = subscriptionsByState;
}
@Override
public String toString() {
return feedId + " " + state + " " + type + " " + errorReason + " " + subscriptionsByState;
}
}The function that reads a feed's results:
/** Reads the feed as it is now, and counts its card subscriptions by state. */
export async function readFeedResults(astrada: Astrada, feedId: string): Promise<FeedResults> {
const feed = await astrada.networkBulkFeeds.get(feedId);
const subscriptionsByState: Record<string, number> = {};
for await (const subscription of astrada.cardSubscriptions.listAll({ networkBulkFeedId: feedId, limit: 100 })) {
subscriptionsByState[subscription.state] = (subscriptionsByState[subscription.state] ?? 0) + 1;
}
return {
feedId: feed.id,
state: feed.state,
type: feed.type ?? null,
errorReason: feed.errorReason ?? null,
subscriptionsByState,
};
}def read_feed_results(client: astrada.Astrada, feed_id: str) -> FeedResults:
"""Reads the feed as it is now, and counts its card subscriptions by state."""
feed = client.network_bulk_feeds.get(feed_id)
results = FeedResults(str(feed.id), feed.state, feed.type, feed.error_reason)
for subscription in client.card_subscriptions.list_all(network_bulk_feed_id=feed_id, limit=100):
results.subscriptions_by_state[subscription.state] = results.subscriptions_by_state.get(subscription.state, 0) + 1
return results/** Reads the feed as it is now, and counts its card subscriptions by state. */
public static FeedResults readFeedResults(ApiClient client, UUID feedId) {
NetworkBulkFeeds feed = client.networkBulkFeeds().get(feedId);
Map<String, Integer> byState = new TreeMap<>();
for (CardSubscription subscription : client.cardSubscriptions().listAll(ListCardSubscriptionsRequest.builder()
.networkBulkFeedId(feedId).limit(100).build())) {
byState.merge(subscription.getStateRawValue(), 1, Integer::sum);
}
return new FeedResults(feed.getId(), feed.getStateRawValue(), feed.getTypeRawValue(), feed.getErrorReason(), byState);
}Handle the state change in your worker
Call this from the worker of recipe 1. It ignores other event types and is safe to repeat.
/**
* The worker step for `networkbulkfeed.statechanged`: call it from recipe 1's `work`. Returns the
* feed's results, or undefined for another event type. Safe to repeat.
*/
export async function onBulkFeedEvent(
astrada: Astrada,
job: WebhookJob,
report: (results: FeedResults, change: { oldState: string; newState: string }) => Promise<void>,
): Promise<FeedResults | undefined> {
if (job.event.type !== 'networkbulkfeed.statechanged') return undefined;
const data = job.event.data as { id?: unknown; oldState?: unknown; newState?: unknown };
if (typeof data.id !== 'string') return undefined;
const results = await readFeedResults(astrada, data.id);
await report(results, { oldState: String(data.oldState), newState: String(data.newState) });
return results;
}def on_bulk_feed_event(
client: astrada.Astrada,
job: Any,
report: Callable[[FeedResults, Dict[str, str]], None],
) -> Optional[FeedResults]:
"""The worker step for `networkbulkfeed.statechanged`: call it from recipe 1's `work` with
its job (`job.event` is the verified event). Returns the feed's results, or None for another
event type. Safe to repeat."""
event: astrada.WebhookEvent[Any] = job.event
if event.type != "networkbulkfeed.statechanged" or not isinstance(event.raw, dict):
return None
feed_id = event.raw.get("id")
if not isinstance(feed_id, str):
return None
results = read_feed_results(client, feed_id)
report(results, {"old_state": str(event.raw.get("oldState")), "new_state": str(event.raw.get("newState"))})
return results/**
* The worker step for {@code networkbulkfeed.statechanged}: call it from recipe 1's {@code work}
* with its job's event. Returns the feed's results, or null for another event type. Safe to repeat.
*/
public static FeedResults onBulkFeedEvent(ApiClient client, WebhookEvent event, BiConsumer<FeedResults, Map<String, String>> report) {
if (!"networkbulkfeed.statechanged".equals(event.getType())) {
return null;
}
JsonObject data = event.getData();
JsonElement id = data.get("id");
if (id == null || !id.isJsonPrimitive()) {
return null;
}
FeedResults results = readFeedResults(client, UUID.fromString(id.getAsString()));
Map<String, String> change = new TreeMap<>();
for (String key : List.of("oldState", "newState")) {
JsonElement state = data.get(key);
// Missing or JSON null reads as "null" rather than throwing in the worker.
change.put(key, state == null || state.isJsonNull() ? "null" : state.getAsString());
}
report.accept(results, change);
return results;
}Whole example files: TypeScript, Python, Java.
What to expect
The first run prints the new feed in state submitted, and a second run finds the same feed. Once the network sends cards, your worker gets networkbulkfeed.statechanged with the old and new state, and the results count the feed's card subscriptions by state.
Read more
- Network Bulk Enrollment: setting up bulk enrollment with each network.
- Testing Bulk Enrollment: the sandbox simulation, step by step.
- Retry a create safely: idempotency keys in the SDKs.
Updated 27 minutes ago
