This commit is contained in:
shafi54 2026-11-14 21:26:25 +05:30
parent 5e658c8d3a
commit f5e5818e64
14 changed files with 226 additions and 83 deletions

File diff suppressed because one or more lines are too long

View file

@ -196,8 +196,7 @@ export default function EditProduct() {
newImageUrls: allUploadUrls,
} as any)
await refetch()
await refetchProducts()
await Promise.all([refetch(), refetchProducts()])
Alert.alert('Success', 'Product updated successfully!')
productFormRef.current?.clearImages()
} catch (error: any) {
@ -241,8 +240,7 @@ export default function EditProduct() {
deletedImageKeys: [],
newImageUrls: [],
} as any)
await refetch()
await refetchProducts()
await Promise.all([refetch(), refetchProducts()])
Alert.alert('Success', 'Market data updated for your region')
} catch (error: any) {
Alert.alert('Error', error.message || 'Failed to update product')

View file

@ -61,8 +61,10 @@ export const StaffAuthProvider = ({ children }: { children: ReactNode }) => {
{ name, password },
{
onSuccess: async (data) => {
await saveJWT(data.token);
await saveStaff(data.staff);
await Promise.all([
saveJWT(data.token),
saveStaff(data.staff),
]);
setStaff(data.staff);
setIsLoggedIn(true);
// A push tapped while signed out waits here; land on it first.
@ -77,8 +79,10 @@ export const StaffAuthProvider = ({ children }: { children: ReactNode }) => {
};
const logout = async () => {
await deleteJWT();
await deleteStaff();
await Promise.all([
deleteJWT(),
deleteStaff(),
]);
setIsLoggedIn(false);
setStaff(null);
queryClient.clear();

View file

@ -189,8 +189,7 @@ function EditProduct() {
newImageUrls: allUploadUrls,
} as any)
await refetch()
await refetchProducts()
await Promise.all([refetch(), refetchProducts()])
window.alert('Product updated successfully!')
productFormRef.current?.clearImages()
} catch (error: any) {
@ -233,8 +232,7 @@ function EditProduct() {
deletedImageKeys: [],
newImageUrls: [],
} as any)
await refetch()
await refetchProducts()
await Promise.all([refetch(), refetchProducts()])
window.alert('Market data updated for your region')
} catch (error: any) {
window.alert(error.message || 'Failed to update product')

View file

@ -40,15 +40,20 @@ export async function initializeProducts(regionId: number): Promise<void> {
try {
console.log('Initializing product store in Redis...')
// Fetch all products with full details (similar to productMega logic)
const productsData = await getAllProductsForCache(regionId)
// All five cache slices are independent: fetch them together.
const [productsData, allStores, allDeliverySlots, allSpecialDeals, allProductTags] =
await Promise.all([
// All products with full details (similar to productMega logic)
getAllProductsForCache(regionId),
getAllStoresForCache(regionId),
// Delivery slots, excluding full capacity slots.
getAllDeliverySlotsForCache(regionId),
getAllSpecialDealsForCache(regionId),
getAllProductTagsForCache(regionId),
])
// Fetch all stores
const allStores = await getAllStoresForCache(regionId)
const storeMap = new Map(allStores.map((s) => [s.id, s]))
// Fetch all delivery slots (excluding full capacity slots)
const allDeliverySlots = await getAllDeliverySlotsForCache(regionId)
const deliverySlotsMap = new Map<number, DeliverySlotData[]>()
for (const slot of allDeliverySlots) {
if (!deliverySlotsMap.has(slot.skuId))
@ -56,8 +61,7 @@ export async function initializeProducts(regionId: number): Promise<void> {
deliverySlotsMap.get(slot.skuId)!.push(slot)
}
// Fetch all special deals
const allSpecialDeals = await getAllSpecialDealsForCache(regionId)
// Special deals by sku
const specialDealsMap = new Map<number, SpecialDealData[]>()
for (const deal of allSpecialDeals) {
if (!specialDealsMap.has(deal.skuId))
@ -65,8 +69,7 @@ export async function initializeProducts(regionId: number): Promise<void> {
specialDealsMap.get(deal.skuId)!.push(deal)
}
// Fetch all product tags
const allProductTags = await getAllProductTagsForCache(regionId)
// Tag names by product
const productTagsMap = new Map<number, string[]>()
for (const tag of allProductTags) {
if (!productTagsMap.has(tag.productId))
@ -158,12 +161,25 @@ export async function getAllProducts(regionId: number): Promise<Product[]> {
//
// return products
const productsData = await getAllProductsForCache(regionId)
// All six cache slices are independent: fetch them together.
const [
productsData,
allStores,
allDeliverySlots,
allSpecialDeals,
allProductTags,
allProductCombos,
] = await Promise.all([
getAllProductsForCache(regionId),
getAllStoresForCache(regionId),
getAllDeliverySlotsForCache(regionId),
getAllSpecialDealsForCache(regionId),
getAllProductTagsForCache(regionId),
getAllProductCombosForCache(regionId),
])
const allStores = await getAllStoresForCache(regionId)
const storeMap = new Map(allStores.map((s) => [s.id, s]))
const allDeliverySlots = await getAllDeliverySlotsForCache(regionId)
const deliverySlotsMap = new Map<number, DeliverySlotData[]>()
for (const slot of allDeliverySlots) {
if (!deliverySlotsMap.has(slot.skuId))
@ -171,7 +187,6 @@ export async function getAllProducts(regionId: number): Promise<Product[]> {
deliverySlotsMap.get(slot.skuId)!.push(slot)
}
const allSpecialDeals = await getAllSpecialDealsForCache(regionId)
const specialDealsMap = new Map<number, SpecialDealData[]>()
for (const deal of allSpecialDeals) {
if (!specialDealsMap.has(deal.skuId))
@ -179,7 +194,6 @@ export async function getAllProducts(regionId: number): Promise<Product[]> {
specialDealsMap.get(deal.skuId)!.push(deal)
}
const allProductTags = await getAllProductTagsForCache(regionId)
const productTagsMap = new Map<number, string[]>()
for (const tag of allProductTags) {
if (!productTagsMap.has(tag.productId))
@ -188,7 +202,6 @@ export async function getAllProducts(regionId: number): Promise<Product[]> {
}
const products: Product[] = []
const allProductCombos = await getAllProductCombosForCache(regionId)
const productCombosMap = new Map<number, ProductComboCacheData[]>()
for (const comboItem of allProductCombos) {
if (!productCombosMap.has(comboItem.comboSkuId))

View file

@ -45,11 +45,11 @@ export async function initializeProductTagStore(regionId: number): Promise<void>
try {
console.log('Initializing product tag store in Redis...')
// Fetch all tags
const tagsData = await getAllTagsForCache(regionId)
// Fetch product IDs for each tag
const productTagsData = await getAllTagProductMappings(regionId)
// The tags and their product mappings are independent reads.
const [tagsData, productTagsData] = await Promise.all([
getAllTagsForCache(regionId),
getAllTagProductMappings(regionId),
])
// Group product IDs by tag
const productIdsByTag = new Map<number, number[]>()

View file

@ -81,9 +81,17 @@ export async function getMultipleUserNegativityScores(
//
// return result
// One query per user, all independent: run them together.
const entries = await Promise.all(
userIds.map(async (userId) => ({
userId,
score: await getUserNegativityScoreFromDb(userId),
}))
)
const result: Record<number, number> = {}
for (const userId of userIds) {
result[userId] = await getUserNegativityScoreFromDb(userId)
for (const entry of entries) {
result[entry.userId] = entry.score
}
return result
} catch (error) {

View file

@ -367,9 +367,11 @@ export const productRouter = router({
skus: skuInputs,
} as any, ctx.staffUser!.regionId)
await claimUploadUrls(allUploadUrls)
await scheduleStoreInitialization(ctx.staffUser!.regionId)
// Both are post-write side effects and independent of each other.
await Promise.all([
claimUploadUrls(allUploadUrls),
scheduleStoreInitialization(ctx.staffUser!.regionId),
])
const productWithImageUrls = {
...newProduct,
@ -470,11 +472,12 @@ export const productRouter = router({
throw new ApiError('Product not found', 404)
}
if (uploadsToValidate.length > 0) {
await claimUploadUrls(uploadsToValidate)
}
await scheduleStoreInitialization(ctx.staffUser!.regionId)
await Promise.all([
uploadsToValidate.length > 0
? claimUploadUrls(uploadsToValidate)
: Promise.resolve(),
scheduleStoreInitialization(ctx.staffUser!.regionId),
])
const productWithImageUrls = {
...updatedProduct,
@ -712,9 +715,10 @@ export const productRouter = router({
await replaceTagProducts(ctx.staffUser!.regionId, createdTag.id, productIds)
await claimUploadUrls(uploadUrls)
await scheduleStoreInitialization(ctx.staffUser!.regionId)
await Promise.all([
claimUploadUrls(uploadUrls),
scheduleStoreInitialization(ctx.staffUser!.regionId),
])
const { products, ...createdTagInfo } = createdTag
@ -779,9 +783,10 @@ export const productRouter = router({
await replaceTagProducts(ctx.staffUser!.regionId, id, productIds)
}
await claimUploadUrls(uploadUrls)
await scheduleStoreInitialization(ctx.staffUser!.regionId)
await Promise.all([
claimUploadUrls(uploadUrls),
scheduleStoreInitialization(ctx.staffUser!.regionId),
])
const { products, ...updatedTagInfo } = updatedTag

View file

@ -51,9 +51,12 @@ export const userRouter = {
// Get order stats for each user
const userIds = usersToReturn.map((u: any) => u.id);
const orderCounts = await getOrderCountsByUserIds(ctx.staffUser!.regionId, userIds);
const lastOrders = await getLastOrdersByUserIds(ctx.staffUser!.regionId, userIds);
const suspensionStatuses = await getSuspensionStatusesByUserIds(ctx.staffUser!.regionId, userIds);
// The three per-user stats are independent reads.
const [orderCounts, lastOrders, suspensionStatuses] = await Promise.all([
getOrderCountsByUserIds(ctx.staffUser!.regionId, userIds),
getLastOrdersByUserIds(ctx.staffUser!.regionId, userIds),
getSuspensionStatusesByUserIds(ctx.staffUser!.regionId, userIds),
]);
// Create lookup maps
const orderCountMap = new Map(orderCounts.map(o => [o.userId, o.totalOrders]));
@ -92,18 +95,19 @@ export const userRouter = {
throw new ApiError('User not found', 404);
}
// Get user suspension status
const isSuspended = await getUserSuspensionStatus(userId);
// Get all orders for this user
const userOrders = await getUserOrders(ctx.staffUser!.regionId, userId);
// Suspension status and the order list are independent reads.
const [isSuspended, userOrders] = await Promise.all([
getUserSuspensionStatus(userId),
getUserOrders(ctx.staffUser!.regionId, userId),
]);
// Get order status for each order
const orderIds = userOrders.map((o: any) => o.id);
const orderStatuses = await getOrderStatusesByOrderIds(ctx.staffUser!.regionId, orderIds);
// Get item counts for each order
const itemCounts = await getItemCountsByOrderIds(ctx.staffUser!.regionId, orderIds);
// Order status and item counts both key off orderIds; run them together.
const [orderStatuses, itemCounts] = await Promise.all([
getOrderStatusesByOrderIds(ctx.staffUser!.regionId, orderIds),
getItemCountsByOrderIds(ctx.staffUser!.regionId, orderIds),
]);
// Create lookup maps
const statusMap = new Map(orderStatuses.map(s => [s.orderId, s]));
@ -163,10 +167,11 @@ export const userRouter = {
.query(async ({ input, ctx }) => {
const { search } = input;
const usersList = await searchUsers(ctx.staffUser!.regionId, search);
// Get eligible users (have notif_creds entry)
const eligibleUsers = await getAllNotifCreds();
// The user list and the notif_creds lookup are independent.
const [usersList, eligibleUsers] = await Promise.all([
searchUsers(ctx.staffUser!.regionId, search),
getAllNotifCreds(),
]);
const eligibleSet = new Set(eligibleUsers.map(u => u.userId));
@ -203,8 +208,10 @@ export const userRouter = {
if (userIds.length === 0) {
// Send to all users - get tokens from both logged-in and unlogged users
const loggedInTokens = await getAllNotifCreds();
const unloggedTokens = await getAllUnloggedTokens();
const [loggedInTokens, unloggedTokens] = await Promise.all([
getAllNotifCreds(),
getAllUnloggedTokens(),
]);
tokens = [
...loggedInTokens.map(t => t.token),

View file

@ -450,8 +450,10 @@ export const orderRouter = router({
const userId = ctx.user.userId;
const offset = (page - 1) * pageSize;
const totalCount = await getUserOrderCount(userId);
const userOrders = await getUserOrdersWithRelations(userId, offset, pageSize);
const [totalCount, userOrders] = await Promise.all([
getUserOrderCount(userId),
getUserOrdersWithRelations(userId, offset, pageSize),
]);
const mappedOrders = await Promise.all(
userOrders.map(async (order) => {

View file

@ -194,8 +194,8 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
const onRefresh = async () => {
setRefreshing(true);
await refetch(); // Refetch product details
await loadReviews(true); // Reset and reload reviews
// Product details and reviews are independent: refresh them together.
await Promise.all([refetch(), loadReviews(true)]);
setRefreshing(false);
};

View file

@ -27,9 +27,12 @@ const PendingAddressSync: React.FC = () => {
isSyncing.current = true
try {
await createAddress.mutateAsync(pending)
await clearPendingAddress()
await utils.user.address.getUserAddresses.invalidate()
await utils.user.address.getDefaultAddress.invalidate()
// The address is saved; clear the draft and refresh both lists together.
await Promise.all([
clearPendingAddress(),
utils.user.address.getUserAddresses.invalidate(),
utils.user.address.getDefaultAddress.invalidate(),
])
} catch {
// Leave the draft in place; a later authenticated mount retries it.
} finally {

View file

@ -198,8 +198,10 @@ export const AuthProvider: React.FC<ReactParentComponent> = ({ children }) => {
try {
setAuthState(prev => ({ ...prev, isLoading: true }));
await saveAuthToken(token);
await saveUserId(user.id.toString());
await Promise.all([
saveAuthToken(token),
saveUserId(user.id.toString()),
]);
setAuthState({
user: {
@ -232,8 +234,10 @@ export const AuthProvider: React.FC<ReactParentComponent> = ({ children }) => {
// const response = loginMutation.mutate(credentials);
const { token, user } = response.data;
await saveAuthToken(token);
await saveUserId(user.id.toString());
await Promise.all([
saveAuthToken(token),
saveUserId(user.id.toString()),
]);
setAuthState({
user: {
@ -266,8 +270,10 @@ export const AuthProvider: React.FC<ReactParentComponent> = ({ children }) => {
const response = await registerMutation.mutateAsync(data);
const { token, user } = response;
await saveAuthToken(token);
await saveUserId(user.id.toString());
await Promise.all([
saveAuthToken(token),
saveUserId(user.id.toString()),
]);
setAuthState({
user: {

View file

@ -936,3 +936,102 @@ admin order-details screens (RN admin-ui + web admin-web).
+ AOD-26: delivered timestamp renders when order.deliveredAt is set
+ AOD-27: no delivered timestamp before delivery
+ AOD-28: per-item packed timestamp renders only when packagedAt is set
[2026-11-14 11:21:51 IST] intrv.java: print numbers 1 to 10 using Java streams.
--- intrv.java (new)
+ class intrv with static printOneToTen() using IntStream.rangeClosed(1, 10).forEach(System.out::println)
+ main() invoking printOneToTen()
[2026-11-14 11:27:23 IST] intrv.java: extract company name before the first hyphen.
--- intrv.java
+ import java.util.Arrays
+ static String extractCompany(String input): null/blank guard, input.split("-", 2)[0].trim()
+ static String extractCompanyStream(String input): Arrays.stream(input.split("-", 2)).findFirst().orElse("")
~ main() now also demos both on "Infosys-Interview 2028"
[2026-11-14 11:27:53 IST] intrv.java: company extraction now stream-only.
--- intrv.java
- remove non-stream extractCompany
~ extractCompanyStream renamed to extractCompany; body is a single Arrays.stream(...).findFirst().orElse("") pipeline
~ main() calls extractCompany only
[2026-11-14 11:58:07 IST] intrv.java: extractCompany rewritten with an enhanced for loop.
--- intrv.java
~ extractCompany: drop Arrays.stream/split pipeline; split once and walk the
segments with a `for (String part : parts)` loop, returning the first non-blank
trimmed segment ("" when none)
- drop now-unused `import java.util.Arrays` (IntStream import stays for printOneToTen)
[2026-11-14 21:20:45 IST] perf: Promise.all for verified-independent sequential awaits.
Read-only waterfalls and independent storage/refetch pairs that the audit
found. No ordering-dependent pair was changed (validate->write, write->read,
mutate->refetch, fetch->reload stay sequential).
--- apps/backend/src/stores/product-store.ts
initializeProducts: 5 cache reads -> one Promise.all
- const productsData = await getAllProductsForCache(regionId)
- const allStores = await getAllStoresForCache(regionId)
- const allDeliverySlots = await getAllDeliverySlotsForCache(regionId)
- const allSpecialDeals = await getAllSpecialDealsForCache(regionId)
- const allProductTags = await getAllProductTagsForCache(regionId)
+ const [productsData, allStores, allDeliverySlots, allSpecialDeals, allProductTags] =
+ await Promise.all([...same five calls...])
getAllProducts: 6 cache reads -> one Promise.all (adds getAllProductCombosForCache)
--- apps/backend/src/stores/product-tag-store.ts
- const tagsData = await getAllTagsForCache(regionId)
- const productTagsData = await getAllTagProductMappings(regionId)
+ const [tagsData, productTagsData] = await Promise.all([
+ getAllTagsForCache(regionId),
+ getAllTagProductMappings(regionId),
+ ])
--- apps/backend/src/stores/user-negativity-store.ts
loop of per-user awaits -> Promise.all over userIds, then fill the record.
--- apps/backend/src/trpc/apis/admin-apis/apis/user.ts
getAllUsers: order counts / last orders / suspension -> Promise.all
getUserDetails: suspension + orders -> Promise.all; statuses + item counts -> Promise.all
getUsersForNotification: searchUsers + getAllNotifCreds -> Promise.all
sendNotification: logged-in + unlogged tokens -> Promise.all
--- apps/backend/src/trpc/apis/user-apis/apis/order.ts
- const totalCount = await getUserOrderCount(userId);
- const userOrders = await getUserOrdersWithRelations(userId, offset, pageSize);
+ const [totalCount, userOrders] = await Promise.all([...])
--- apps/backend/src/trpc/apis/admin-apis/apis/product.ts
claimUploadUrls + scheduleStoreInitialization -> Promise.all at 4 sites
(create product, update product, create tag, update tag). create/update and
replaceTagProducts stay before the batch because the cache rebuild reads them.
--- apps/user-ui/src/contexts/AuthContext.tsx
saveAuthToken + saveUserId -> Promise.all (3 sites: loginWithToken/login/register)
--- apps/admin-ui/components/context/staff-auth-context.tsx
saveJWT + saveStaff, deleteJWT + deleteStaff -> Promise.all
--- apps/admin-ui/app/(drawer)/dashboard/products/edit.tsx
--- apps/admin-web/src/routes/dashboard.products.edit.tsx
refetch() + refetchProducts() -> Promise.all (2 sites each; web counterpart)
--- apps/user-ui/components/ProductDetail.tsx
onRefresh: refetch() + loadReviews(true) -> Promise.all
--- apps/user-ui/src/components/PendingAddressSync.tsx
clearPendingAddress + getUserAddresses/getDefaultAddress invalidations -> Promise.all
(the createAddress mutation still completes first)
Skipped on purpose:
- write -> scheduleStoreInitialization pairs (store/banner/global-store CRUD):
single enqueue after commit, negligible gain.
- cloud_cache version bumpers: independent but D1 serializes writes anyway.
- per-region loops (createAllCacheFiles, initializeAllStores, gen-store,
flash cron): deliberate batching, not a missed parallel await.
- getAuthToken + getCurrentUserId (AuthContext:70): getCurrentUserId re-reads
the token; needs a refactor, not Promise.all.