高速資料流與高效併發:使用 Rust 和 Tokio 減少累積的等待

價格更新已經到達您的交易應用,但要過一段時間才能影響決策。隨著更新數量增加,應用狀態與市場之間的差距進一步擴大。出現這種症狀時,需要同時檢查資料的獲取方式及其到達後的處理路徑。
接收更新、提取資料、更新狀態、檢查條件、儲存記錄。如果多個階段都要等待前一步操作完成才能繼續,資料到達決策邏輯所需的時間就會變長。如果後續更新在此期間持續到達,這些等待還會進一步累積。要讓高速資料流轉化為響應迅速的應用,需要在保持必要順序的同時,分離可以獨立推進的工作。
本文面向使用 TypeScript、Python 或類似語言實現價格接收與決策邏輯的開發者。我們跟隨價格源中的一條更新,觀察應用如何接收它、將其應用於狀態、檢查條件,並將結果保留為輔助記錄。儲存目標是應用側的檔案或資料庫;本文可執行的示例使用檔案。
本文以輔助儲存為例,將有序處理與可以分別推進的工作之間的邊界落實到程式碼中。我們首先診斷接收路徑在等待什麼,並對現有 TypeScript 實現作出合理改進。然後考察 Rust/Tokio 如何讓您控制所有權、共享狀態、執行位置和併發上限,這是我們構建低延遲接收與決策引擎時首先推薦的選擇。本文透過實現與驗證,繼續展開上一篇低延遲架構文章中對熱路徑和輔助工作的分離。
此處儲存的是輔助記錄,無須在下一次決策前完成持久化。對於正確性所依賴的步驟,例如傳送訂單前必須完成的持久化,不能用同樣的替換方式將其移除。在接收與儲存已經分離的應用中,問題也可能是未完成儲存的數量不斷增加。請追蹤呼叫方,確定屬於哪種情況。
本文的目標是幫助您認識產生等待的處理模式,以及如何重構這些模式。您應能夠讀懂自己程式碼中的依賴關係,判斷哪些順序必須保留、哪些工作可以分別推進。以價格 100 → 101 為例的圖示說明原理,小型可執行示例則驗證決策結果、順序和記錄保留。本文不報告真實環境中的改善百分比,也不按速度對語言排名。
即使交易條件編寫正確,仍然需要調查新價格到達這些條件之前的等待。追蹤下一次決策能夠繼續前必須完成的操作,再選擇哪些部分需要保持有序、哪些可以分別推進。掌握這些知識後,在請求 AI 修復時,您也能夠準確告訴它應調查哪裡、保留哪些條件,並評估其建議的更改是否確實有幫助。
本文的主要主題是併發:在等待檔案或網路通訊等輸入/輸出(I/O)期間,推進其他工作。我們將其與並行區分開,後者指在多個 CPU 核心上同時執行計算。無論 Rust 還是 TypeScript,僅僅寫上
async 都不會把繁重的計算移到另一個 CPU 上。[S03][S07][S08][S13]第 1、2 節將症狀與設計聯絡起來。第 3、4 節使用 TypeScript 和 Rust 跟蹤相同的六個價格。第 5、6 節討論佇列滿、故障和關閉;第 7 節將設計對映到實際接收程式碼;第 8 節提供執行步驟。如果您從診斷現有 TypeScript 或 Python 程式碼開始,可以先閱讀第 1–3 節,再閱讀第 5–8 節,在考慮 Rust 實現時返回第 4 節。如果希望從原理入手,可以結合第 1、2、5、6 節的文字和圖示,跟蹤決策與儲存的推進過程。
第 10 節是供您在自己的倉庫中工作時完整複製的附錄。理解正文中的原因和需要保留的條件後,可以用它請求 AI 智慧體診斷、修改並驗證您的程式碼。
輕觸或點選圖示,即可以原始尺寸開啟圖片。
1. 下一條更新能夠繼續處理前,必須先完成什麼?
首先檢查什麼條件允許下一條更新開始處理。以下程式碼應用價格並檢查交易條件,然後儲存一條輔助記錄。
typescript
for await (const update of updates) {
state.apply(update);
const decision = decide(state);
await saveAuxiliary({ seq: update.seq, price: state.price, decision });
}for await (const update of updates) {
state.apply(update);
const decision = decide(state);
await saveAuxiliary({ seq: update.seq, price: state.price, decision });
}非同步 I/O 尚未完成時,Node.js 事件迴圈可以推進其他工作。但這個迴圈在儲存的 Promise 兌現之前,不會進入下一次迭代。即使儲存價格 100 的記錄期間,價格 101 的更新已經到達,這個迴圈也要等儲存完成後才能使用價格 101。[S12][S14]
檢查現有程式碼並進行小規模本地回放,以確認是否存在這種依賴關係。針對同一個更新 ID,對照以下時間戳。
| 時間戳 | 在程式碼中的測量位置 | 檢查內容 |
|---|---|---|
| 處理開始 | 取出更新後立即記錄 | 是否必須等前一次儲存完成,才能取出下一條更新 |
| 條件檢查完成 | 應用狀態並檢查條件後立即記錄 | 是狀態應用與條件檢查耗時較長,還是處理在開始前就受到阻塞 |
| 儲存開始與完成 | 呼叫儲存前和儲存完成後立即記錄 | 等待儲存是否延遲了後續處理的開始 |
例如,在只回放一小組固定輸入時,可以按以下方式設定測量點。本示例展示的是測量位置。
finiteUpdates 最多包含六個輸入,trace 只保留這六個輸入的測量結果;顯示或檔案輸出在回放結束後進行。如果儲存失敗,不記錄完成時間,並讓異常傳遞給現有的故障處理程式。typescript
const trace = [];
for (const update of finiteUpdates) {
const started = performance.now();
state.apply(update);
const decision = decide(state);
const decided = performance.now();
const record = { seq: update.seq, price: state.price, decision };
const saveStarted = performance.now();
let saved: number | undefined;
try {
await saveAuxiliary(record);
saved = performance.now();
} finally {
trace.push({ seq: update.seq, started, decided, saveStarted, saved });
}
}const trace = [];
for (const update of finiteUpdates) {
const started = performance.now();
state.apply(update);
const decision = decide(state);
const decided = performance.now();
const record = { seq: update.seq, price: state.price, decision };
const saveStarted = performance.now();
let saved: number | undefined;
try {
await saveAuxiliary(record);
saved = performance.now();
} finally {
trace.push({ seq: update.seq, started, decided, saveStarted, saved });
}
}如果下一條更新在前一次儲存完成後才開始處理,並且呼叫關係也顯示相同依賴,就可以確認處理在等待儲存。但僅憑這一點,不能斷定所有等待都由儲存造成。輸入本身可能尚未到達,因此還應比較預定到達時間或可獲取的接收時間戳。本文的小型可執行示例在開始時就已準備好相同的六個輸入,並未重現實際到達間隔。使用真實資料時,還應記錄捕獲的輸入序列以及測量開始的邊界。
對於實際資料流,要說明“接收時間”是指套接字收到資料、SDK 回撥開始,還是應用取出更新的時刻。未檢查時鐘偏差前,不要用本地時鐘減去伺服器傳送時間戳。
在 SDK 回撥中應檢視哪裡
SDK 是讓應用能夠使用資料接收等功能的庫。如果您向 SDK 註冊一個每次更新都會被呼叫的函式,即回撥,也應在該入口記錄更新 ID 和時間戳。在入口處記錄
received,並將 state.apply 真正開始的時刻單獨記錄為 started。如果兩者之間還有您自己的處理佇列,更新可能已經到達回撥,但尚未開始應用狀態。例如,考慮僅包含兩條更新的本地回放:讓價格 100 的儲存保持未完成,並在此期間送入價格 101。將以下差異與上面的
started、decided 和 saved 時間戳進行對照。| 觀察項 | 決策與儲存在同一個迴圈中 | 每個事件都有一個非同步回撥 |
|---|---|---|
| 在價格 100 儲存完成前收到價格 101 | 接收已被記錄,但價格 101 的狀態應用尚未開始 | 價格 101 的回撥可能被呼叫,從而推進狀態應用與條件檢查 |
| 價格 101 的條件檢查開始 | 價格 100 已儲存完成 | 價格 100 可能仍在儲存中 |
| 接下來追蹤什麼 | 接收與決策處理之間的佇列,以及等待儲存完成的迴圈 | 重疊儲存的數量、它們的完成順序,以及 await 前後的狀態更新 |
Node.js
EventEmitter 在呼叫下一個事件前,不會等待非同步監聽器返回的 Promise 完成。[S21] 要判斷 SDK 是否另行等待 Promise,需要將其呼叫方實現與觀察結果對照。第 7 節檢查 Solana Stream SDK 的實際呼叫模式。如果價格 100 尚未儲存完成,價格 101 的決策就已經推進,就不能將這條路徑診斷為儲存阻塞了下一次決策。在後一種情況下,如果前一次儲存尚未完成,新輸入就持續到達,未完成的儲存會相互重疊。儲存也可能不按順序完成,因此設計需要控制啟動數量和順序。本文采用一個寫入器和一個有界佇列。我們還在執行順序示例中,用兩條固定更新和手動完成的模擬儲存檢查了這種差異。這是在診斷允許下一次決策開始的條件,不是在比較耗時。其中既沒有真實 SDK 連線,也沒有真實 I/O 的效能測量。
檢查何時可以推遲儲存
儲存並非等待的唯一來源。應測量每個階段,選擇能夠針對原因的更改。
| 檢查區域 | 延遲來源 | 可以考慮更改的邊界 |
|---|---|---|
| 儲存到資料庫或檔案 | 等待 I/O 完成的時間 | 將允許在下一次條件檢查之後完成的輔助儲存交給單獨的處理過程 |
| JSON 編碼、壓縮與計算 | 佔用 CPU 的時間 | 減少傳遞的資料,並在必要時將工作移至用於 CPU 工作的執行資源 |
| 有界佇列 | 等待容量的時間 | 檢查容量、輸入量、處理能力和佇列滿時的策略 |
| Mutex 及類似機制 | 等待鎖釋放的時間 | 重新審視誰負責更新狀態、加鎖範圍以及持鎖時長 |
狀態更新和使用該狀態的條件檢查有其順序。將每個階段獨立並行化並不足夠。此處移除的依賴,是等待下一次條件檢查並不需要的輔助儲存。檔名或“日誌”標籤不能決定某條記錄是否屬於輔助記錄。
| 儲存內容示例 | 在規格與程式碼中檢查什麼 | 關於分離的判斷 |
|---|---|---|
| 用於觀察的價格與決策歷史 | 下一次決策能否使用記憶體狀態,並容忍延遲儲存?其他處理或恢復路徑是否依賴這次儲存完成? | 確認這些條件後,可以考慮本文所示的分離方式 |
| 防止重啟後重復下單的記錄 | 約定是否要求傳送訂單前成功持久化識別符號? | 如果有此要求,傳送訂單前必須保留對儲存的等待 |
| 餘額快取或報價歷史 | 這是可以重新獲取的顯示資料,還是下一次結算、餘額更新或恢復的依據? | 追蹤使用方與恢復處理後再作決定 |
即使記錄的是同一價格和決策結果,僅用於觀察還是作為恢復依據,也會要求不同的處理方式。檢查儲存結果的讀取位置、故障處理、重啟處理、規格和現有測試。如果依賴關係不清楚,應在調查期間保留對儲存的等待。這個可執行示例涵蓋交易條件的計算,並不涵蓋根據決策結果傳送訂單的前提條件。
2. 讓相同的工作分別推進
一邊儲存價格 100 的記錄,一邊使用價格 101 檢查交易條件。讓我們看看這兩項操作分別推進時,減少的是哪一段等待。
決策規則是:前一個價格低於 101 且當前價格至少為 101 時為
enter;反向變化時為 exit;其他情況和第一條更新均為 hold。這條規則需要前一個狀態,因此也說明了更新順序為何重要。它只是用於比較設計的簡單條件檢查,不會傳送訂單。圖 1 展示了等待儲存完成的迴圈。這是一個解釋模型,假設價格 100 在 0 ms 到達,價格 101 在 10 ms 到達,條件檢查耗時 1 ms,儲存每條記錄耗時 30 ms。輸入時間與處理開始時間是不同的,兩種方式收到的是相同更新。圖中的時間是設定值,並非測量結果。
更改前,迴圈為價格 100 判定
hold,然後從 1 ms 到 31 ms 等待儲存。價格 101 在 10 ms 到達,但其條件檢查直到 31 ms 才能開始,在 32 ms 產生 enter。從輸入到條件檢查完成的時間為 22 ms。更改後,輸入側將已經確定的價格與決策結果交給寫入器,隨後繼續處理下一條更新。價格 101 在 10 ms 到達時,輸入側開始檢查條件,並在 11 ms 產生
enter。從輸入到條件檢查完成的時間為 1 ms。與此同時,寫入器仍在儲存價格 100 的記錄。兩種方式都按順序評估相同的兩條更新,並按順序儲存相同的兩條記錄。更改前全部儲存在 62 ms 完成,更改後在 61 ms 完成;兩次各 30 ms 的儲存工作依然存在。得到改善的是下一次條件檢查等待前一次儲存所花費的時間。
如果前一次輔助儲存的完成阻礙了已經到達的後續更新的決策,這種設計就可能有幫助。如果下一次決策不依賴該次儲存成功,佇列尚有空間,且決策處理能夠執行,那麼下一次決策便可以在儲存期間繼續。移除不必要的完成依賴,才是可能降低延遲的原因。交接和排程也會增加成本,因此應在自己的實現中使用相同輸入和工作,驗證改善幅度。
但是,如果輸入持續超過儲存能力,有限佇列會填滿,輸入側也會等待。僅僅分離儲存不會增加目標端的處理能力。如果下一次決策原本就能繼續,或者主要原因是 CPU 計算或鎖,則需要其他更改。既要檢查是否把工作交給單獨的處理過程,也要檢查阻礙決策的依賴是否減少。[S04][S06][S07]
寫入器收到的是該時刻已經確定的價格與決策結果。對於第一條更新,就是類似
{ seq: 0, price: 100, decision: "hold" } 的記錄。即使下一條更新把 state.price 改為 101,正在儲存的記錄中的價格仍然是 100。相反,如果傳遞可變的 state 本身並在儲存時再次讀取價格,就可能記錄成另一條更新的價格。正常完成時,所有記錄都會儲存。佇列滿時,輸入側持有當前記錄並等待空間。如果寫入器關閉或失敗,需要核對已儲存內容和尚未完成的內容。第 5、6 節討論這些邊界。
3. 在 TypeScript 中分離狀態更新與儲存
現有 TypeScript 程式碼也可以讓狀態更新與輔助儲存分別推進。這裡使用六個有限輸入:100 → 101 → 102 → 100 → 101 → 99。決策依次為
hold、enter、hold、exit、enter 和 exit。所有輸入在開始時已經準備好;沒有用於模擬到達的計時器,也沒有為了減慢儲存而人為加入的等待。每條記錄都寫入真實的 JSONL 檔案,儲存會一直等待到 datasync() 完成。這個小型可執行示例用於追蹤決策順序、儲存交接、佇列滿、故障和關閉。六個輸入的處理速度不能證明語言排名或生產效能。完整版本見 TypeScript 實現,其輸入為 prices.json。
首先,在一個函式中結合狀態更新與記錄建立。兩種方式使用相同的
decide,並且只有輸入側更新 previousPrice。typescript
export function decide(state: State, input: Input): Record {
let decision: Decision = "hold";
if (state.previousPrice !== undefined && state.previousPrice < 101 && input.price >= 101) decision = "enter";
else if (state.previousPrice !== undefined && state.previousPrice >= 101 && input.price < 101) decision = "exit";
state.previousPrice = input.price;
return Object.freeze({ seq: input.seq, price: input.price, decision });
}export function decide(state: State, input: Input): Record {
let decision: Decision = "hold";
if (state.previousPrice !== undefined && state.previousPrice < 101 && input.price >= 101) decision = "enter";
else if (state.previousPrice !== undefined && state.previousPrice >= 101 && input.price < 101) decision = "exit";
state.previousPrice = input.price;
return Object.freeze({ seq: input.seq, price: input.price, decision });
}這條記錄的欄位是數字和字串,建立後不再修改。兩種方式也都在輸入側透過相同的
encode 進行 JSON 轉換。寫入器收到的是該輸入已經確定的記錄與 JSON 字串。它不會在市場狀態改變後再次讀取該狀態。分離前的流程如下。為了只展示依賴關係,省略了報告相關程式碼行。
typescript
const record = decide(state, update);
const pending = encode(record);
await save(file, pending, options);
// この保存が終わってから、次のupdateへ進む。const record = decide(state, update);
const pending = encode(record);
await save(file, pending, options);
// この保存が終わってから、次のupdateへ進む。分離後,啟動一個寫入器和一個有界佇列。圖 2 中,輸入與決策處理位於左側,佇列位於中間,寫入器位於右側。狀態仍由輸入側更新;等待儲存完成的工作則移交給單獨的角色。
完整版本中,以下一行在輸入迴圈之前啟動一次寫入器,並保留返回的 Promise。
queue 存在於分離版本中。此時,輸入迴圈繼續執行,不等待寫入器完成。typescript
const writerTask = queue === undefined ? undefined : writer(queue, file, options, emit);const writerTask = queue === undefined ? undefined : writer(queue, file, options, emit);繼續處理下一條更新前,輸入側會檢查
queue.put 的結果。這裡的 put 是此可執行示例中的方法,並非標準 Node.js API。有空間時,它接受記錄;佇列滿時,它保留當前記錄並等待。寫入器取出一條記錄後,輸入側就能將記錄放入空出的槽位並繼續。這段程式碼只有一個輸入迴圈,在繼續下一條更新前等待
put。如果只是將它放入 SDK 為每條更新呼叫、且不等待其 Promise 完成的回撥中,也會為每條更新建立一個新的入隊等待。第 7 節檢查呼叫方和上游保留方式。從這裡開始,“已接受”表示佇列已取得記錄的所有權,與儲存開始和儲存完成分別計數。typescript
const wasAccepted = await queue.put(pending, () => emit("full_wait", record.seq));
if (!wasAccepted) {
unaccepted.push(record);
status = "closed";
break;
}
accepted.push(record.seq);const wasAccepted = await queue.put(pending, () => emit("full_wait", record.seq));
if (!wasAccepted) {
unaccepted.push(record);
status = "closed";
break;
}
accepted.push(record.seq);false 表示目標佇列已關閉,無法接受記錄。應保留這條記錄並停止處理後續輸入。這不同於佇列滿時等待空間。emit 和 accepted 為這些有限輸入記錄執行順序和接受數量。只啟動一個寫入器,並將其 Promise 保留在
writerTask 中。不要為每個輸入建立新的儲存任務。因為輸入側也逐條等待 put,最多隻有一個生產者等待空間。這可以防止未完成的儲存離開佇列後在其他位置不斷增長。寫入器對取出的每條記錄呼叫共享的
save。這個函式在兩種方式中執行的真實 I/O 完全相同。typescript
await file.writeFile(item.bytes);
await file.datasync();await file.writeFile(item.bytes);
await file.datasync();寫入器只有在儲存完成後才取下一條記錄,從而保持該檔案的寫入順序。為了分離非同步 I/O,無須為每條記錄建立一個 JavaScript worker。如果希望把 CPU 密集型 JavaScript 計算移至其他執行緒,可以考慮工作執行緒。[S12][S13]
輸入結束後,關閉佇列以停止進一步提交,並等待寫入器的結果。這裡使用的
close() 不會丟棄剩餘記錄。寫入器持續取出記錄,直到佇列為空,然後退出。輸入異常或提前停止也會進入同一條關閉路徑。typescript
queue?.close();
if (writerTask !== undefined) writes = await writerTask;
try { await file.close(); } catch (error) { fileCloseError = String(error); }queue?.close();
if (writerTask !== undefined) writes = await writerTask;
try { await file.close(); } catch (error) { fileCloseError = String(error); }在完整版本中,這段程式碼位於
finally 內。收到寫入器結果後才關閉檔案。第 6 節討論儲存失敗時的記錄恢復。僅僅把呼叫替換為
void save(record),不能控制同時啟動多少次儲存、故障、順序或關閉。本示例中儲存輸入、決策歷史和執行順序的陣列,也只是用於核對最多六個輸入的教學示例。對於持續執行的資料流,應將其替換為明確規定數量或保留上限的記錄方式。將設計對映到現有 Python 程式碼
Python 可以透過
asyncio.Queue(maxsize=...) 和一個寫入器 Task 建立相同的邊界。使用 asyncio.create_task(writer(...)) 啟動一個寫入器並保留該 Task。在 Python 中,僅呼叫非同步函式並不會開始執行,因此還需要正確對應啟動方法。[S15][S16]如果直接執行同步 I/O 或長時間 CPU 工作,即使把工作移到另一個 Task,仍可能佔用同一個事件迴圈。還應檢查實際儲存 API 在哪裡等待、在哪裡執行。[S16]
| 本文采用的設計 | Python 中需要檢查的對應行為 |
|---|---|
| 啟動一個寫入器 | 使用 create_task 啟動一次,不是每條更新啟動一次 |
| 在容量範圍內交接記錄 | 一個輸入生產者使用 await queue.put(record)。佇列滿時,保留當前記錄並等待 |
| 關閉時恢復記錄 | 在 Python 3.13 或更高版本中,處理 QueueShutDown 並保留生產者持有的未被接受記錄 |
| 正常關閉時處理剩餘內容 | 在 Python 3.13 或更高版本中,呼叫 shutdown(immediate=False) 後,繼續用 get() 消費剩餘記錄,並等待寫入器 Task 的結果 |
儲存失敗時,停止新提交,恢復失敗記錄以及佇列中的剩餘記錄。僅有佇列關閉通知,不能保證儲存成功。此表用於指導如何將設計應用於 Python,並非完整的 Python 實現或效能結果。本文針對現有環境提供的可執行示例僅限於 Node.js。
4. 使用 Rust/Tokio 定義所有權與執行邊界
我們繼續使用第 3 節中相同的六個價格。輸入 100 → 101 → 102 → 100 → 101 → 99,得到
hold → enter → hold → exit → enter → exit。沿用圖 2、3 中的價格與記錄 ID,跟蹤 Rust 中的啟動、交接與關閉。[L06]這個 Rust 示例的更改前後版本呼叫相同的
decide、encode 和 save。順序版本在輸入迴圈內完成一次 save(...).await 後才繼續。在分離版本中,輸入側作出決策、編碼 JSON,並將已經確定的記錄交給一個寫入器。這項更改分離了儲存的執行位置,沒有改變所執行的工作。[L06]從一個輸入任務交接給一個寫入器
首先,將以下四項操作與程式碼對應起來。這些角色表示任務職責,不代表為每個角色分別分配一個作業系統執行緒或 CPU 核心。
| 操作 | 在程式碼中追蹤的位置 |
|---|---|
| 啟動一次寫入器 | 使用 mpsc::channel 建立交接通道,將接收端和檔案傳給 tokio::spawn |
| 按順序決策,並確定該時刻的記錄 | 輸入迴圈中的 decide 和 encode。只有這個迴圈更新狀態 |
| 交出當前記錄 | 成功時繼續。遇到 Full 時保留同一條記錄並等待接受。遇到 Closed 時恢復記錄並停止後續輸入 |
| 檢查已接受的儲存是否完成 | 使用 drop(tx) 結束進一步提交,透過 writer_task.await 接收寫入器結果 |
以下程式碼摘自完整可執行版本中的
run_after。其中省略了輸入驗證、檔案建立、狀態與報告陣列初始化、測試停止與觀察,以及最終 Report 的構建。CAPACITY 為 2。這個設定便於使用六個輸入追蹤佇列滿時的行為,並非生產環境的推薦容量。options.failure 和 options.gate 是用於檢查故障與佇列滿的注入設定,正常執行不會使用。rust
let (tx, mut rx) = mpsc::channel(CAPACITY);
let writer_task = tokio::spawn(writer(rx, file, options.failure, options.gate));
for &input in inputs {
let pending = encode(decide(&mut state, input));
decided.push(input.seq);
let sent = match tx.try_send(pending) {
Ok(()) => Ok(()),
Err(mpsc::error::TrySendError::Full(pending)) => {
tx.send(pending).await.map_err(|error| error.0)
}
Err(mpsc::error::TrySendError::Closed(pending)) => Err(pending),
};
match sent {
Ok(()) => accepted.push(input.seq),
Err(pending) => {
unaccepted.push(pending.record);
break;
}
}
}
drop(tx);
let writes = writer_task.await.map_err(|error| {
io::Error::other(format!(
"writer task failed; no complete report: {error}; accepted IDs: {accepted:?}"
))
})?;let (tx, mut rx) = mpsc::channel(CAPACITY);
let writer_task = tokio::spawn(writer(rx, file, options.failure, options.gate));
for &input in inputs {
let pending = encode(decide(&mut state, input));
decided.push(input.seq);
let sent = match tx.try_send(pending) {
Ok(()) => Ok(()),
Err(mpsc::error::TrySendError::Full(pending)) => {
tx.send(pending).await.map_err(|error| error.0)
}
Err(mpsc::error::TrySendError::Closed(pending)) => Err(pending),
};
match sent {
Ok(()) => accepted.push(input.seq),
Err(pending) => {
unaccepted.push(pending.record);
break;
}
}
}
drop(tx);
let writes = writer_task.await.map_err(|error| {
io::Error::other(format!(
"writer task failed; no complete report: {error}; accepted IDs: {accepted:?}"
))
})?;mpsc::channel 建立傳送端 tx 和接收端 rx,tokio::spawn 啟動一個寫入器。接收端與檔案的所有權轉移給寫入器。只有輸入迴圈更新價格 state,它不與寫入器共享。[S03][S04][L06]decide 應用當前價格並確定決策,encode 則將該記錄和 JSON 位元組打包為 Pending。writer 將透過 recv().await 收到的每個專案傳給共享的 save,只有在 write_all → flush → sync_data 完成後才取下一項。儲存不會在價格狀態改變後再次讀取它。[S09][S10][L06]如果
try_send 成功,輸入側就可以繼續下一個價格。佇列滿時,Full(pending) 返回同一個尚未被接受的值。將這個值傳給 send(pending).await,等待容量,不重複決策,也不為每條更新建立另一個等待任務。傳送 Future 在等待期間擁有該記錄。輸入側等待時,Tokio 可以推進寫入器;但如果儲存持續停滯,輸入側也會繼續等待。[S04][S05][L06]如果通道關閉,從
Closed(pending) 或掛起傳送的錯誤中恢復值。map_err(|error| error.0) 提取傳送錯誤持有的未被接受的 Pending,使兩條關閉路徑進入相同的恢復處理。將已經完成決策的記錄保留在 unaccepted 中,不再繼續後續輸入。break 退出輸入迴圈後,執行仍會繼續到 drop(tx) 和 writer_task.await。前者結束進一步提交,後者檢查寫入器的關閉結果。應分別檢查提交成功、儲存完成和任務完成。[S04][S06][S34][L06]本示例不會取消掛起的傳送。如果
select! 的另一個分支或任務中止丟棄了 send Future,它所擁有的記錄也可能丟失。儲存出錯時,寫入器恢復失敗記錄並返回;透過 writes.error 和 Report 中的各個類別檢查結果。例如,如果任務自身發生 panic,且 writer_task.await 返回 JoinError,示例會返回錯誤,而不是完整的 Report。不要將本示例視為保證能從 panic、強制終止或崩潰中恢復。[S04][S34][L06]轉移所有權不需要深複製
Pending 包含已經確定的記錄和一個 Vec<u8>,屬於非 Copy 型別。通道接受它之後,輸入側不能繼續以所有者身份使用同一個值。如果通道已滿或已關閉,輸入側收到返回值,就可以重新處理其所有權。這把“仍由輸入側持有的記錄”和“已交給寫入器的記錄”與型別和程式碼聯絡起來。[S05][S22][L06]這種交接不需要深複製整條記錄。不過,
encode 會為 JSON 位元組分配記憶體。僅僅使用所有權轉移,並不會讓整個系統變成 zero-copy 或完全不分配記憶體。價格示例最多處理六條欄位固定的小記錄。由於只有輸入側持有可變狀態,無須透過 Arc 或 Mutex 與寫入器共享市場狀態。第 7 節會單獨討論將設計適配到變長 Geyser 更新時新增的位元組上限。
Arc、Send/Sync 與 Tokio 承擔不同職責
您可以使用
Arc<Config>,在多個角色之間共享大型不可變配置等資料。Arc::clone 為同一塊記憶體分配新增一個共享所有者,不會深複製內容。安全地併發修改內部值需要另一個機制,而原子引用計數操作也有成本。在配套的 Geyser 回放示例中,Arc 共享位元組預算的 Semaphore,而預算的安全獲取、釋放和關閉由 Semaphore 本身提供。[S01][S11][S30][L04]| 機制 | 控制什麼 | 不會自動保證什麼 |
|---|---|---|
| 所有權轉移 | 哪個角色持有記錄和位元組 | Zero-copy、零分配或儲存成功 |
Arc | 對同一份資料的共享所有權 | 安全地併發修改內部值 |
Send | 型別是否允許擁有的值線上程之間移動 | 在另一個執行緒上執行 |
Sync | 型別是否允許跨執行緒使用共享引用 | 更新順序或不會死鎖 |
| Tokio | 非同步任務、I/O 等待和通道的推進 | 專用 CPU、優先順序或決策截止時間 |
Send 和 Sync 是型別的屬性,Arc 是共享所有權工具,Tokio 是執行執行時。普通 tokio::spawn 要求 Future 及其輸出滿足 Send + 'static。這裡的 'static 是型別約束,用來防止任務依賴短生命週期的借用。它不表示值永遠存活;透過所有權轉移進入任務的值,可以在不再需要時釋放。[S02][S03]這個 Rust 價格示例的更改前後版本都在
current_thread 上執行。即使只有一個非同步執行執行緒,在等待 I/O 時,其他任務仍可推進。檔案 I/O 也會涉及 Tokio 內部的阻塞執行資源,因此這不代表整個程序只使用一個作業系統執行緒。配套的 Geyser 回放示例使用帶兩個 worker 的 multi_thread;請分別記錄這些執行設定。[S08][S09][L04][L06]TypeScript 也能分離工作,為何首先推薦 Rust?
分離儲存的設計同樣可以用 TypeScript 實現。如果只更換語言,卻保留相同的儲存依賴,等待前一次儲存的要求仍然存在。
當需要深入構建一個新的低延遲接收與決策引擎時,我們首先推薦 Rust。它讓您能夠把哪些值被擁有、複製或共享,與型別和交接聯絡起來:只提取決策所需的欄位,將位元組的所有權轉移給儲存過程,固定狀態更新方,並限制 CPU 工作的執行位置和併發度。您可以逐項檢查這些選擇,將改進集中在確有需要的地方。[S01][S02][S07][S11][S22]
例如,如果輸入側成功傳送後還試圖修改同一個
pending,Rust 會在編譯時拒絕這個所有權錯誤。在細化實現時,把單一決策任務與有界佇列的設計,和交接值的型別檢查連線起來,是一個優勢。[S22]對於現有 TypeScript 或 Python 程式碼,應先在當前語言中修正依賴關係,並檢查在所需輸入條件下是否滿足決策截止時間、順序和保留要求。如果分離輔助儲存就能滿足這些要求,可以繼續使用該實現。如果仍不滿足,且解碼或複製等某個特定階段仍有成本,再考慮將該階段提取到 Rust 中。決策時要納入交接與運維成本;並不要求一次性重寫 UI、配置和監控。
不要把首先推薦 Rust 的理由,重新解讀為它在某個特定輸入上具有速度優勢的證據。應將控制複製、分配、共享、同步和執行位置的能力,與實際減少了什麼、減少多少分別說明,並將兩者各自關聯到實現與驗證結果。
5. 佇列滿時持有一條記錄,空間釋放後恢復
有界佇列可以吸收短暫的輸入增長。但容量用盡後,輸入側也必須等待空間。Tokio 的
send().await 和本示例 TypeScript 的 put 都會引入這種等待。分離儲存並不意味著設計在任何情況下都無需等待。[S04]跟隨這六個輸入,觀察它們如何交給容量為 2 的佇列。記錄 ID 0 對應價格 100 的
hold,ID 1 對應價格 101 的 enter,ID 2 對應價格 102 的 hold,ID 3 對應價格 100 的 exit。隨後是 ID 4,對應價格 101 的 enter,以及 ID 5,對應價格 99 的 exit。ID 是輸入順序中的序號,不是價格。寫入器寫入 ID 0 時,ID 1 和 2 填滿佇列的兩個槽位。輸入側已經完成 ID 3 的決策,但還無法交給寫入器。因此,它持有 ID 3 並等待,不繼續處理 ID 4 或更後面的輸入。
ID 0 儲存完成、寫入器取出 ID 1 後,佇列中空出一個槽位。輸入側交出一直保留的 ID 3,然後繼續 ID 4。它不會重複 ID 3 的決策,而是保留同一條記錄並繼續交接。
此時,輸入側只有一項工作在等待。如果繼續為每條更新建立一個等待
send 的任務,只是把無界等待移到了佇列之外。這裡的輸入側會等當前提交完成後,才處理下一條輸入。| 寫入器狀態 | 輸入側行為 |
|---|---|
| 佇列有空間 | 交出已經確定的記錄,並繼續下一條輸入 |
| 佇列已滿,寫入器仍在執行 | 保留當前記錄,等待空間,然後恢復 |
| 寫入器已關閉 | 保留未被接受的記錄,或其恢復來源與 ID,並停止後續輸入 |
佇列滿時的等待稱為背壓。如果輸入持續超過儲存能力,等待時間也會增長。要用有限記憶體保留所有必需記錄,必須決定在哪裡控制負載:讓上游等待、停止接受輸入,或提供可以用於恢復的已儲存輸入。
佇列容量限制的是佇列內部的記錄。正在儲存的記錄、輸入側持有的記錄、變長載荷、接收緩衝區和聚合結果還會消耗額外記憶體。處理真實資料的實現除了數量上限,也需要位元組上限。[S04][S06]
在這個小示例中,所有輸入仍然保留在檔案裡。對於實時 gRPC 或 WebSocket 輸入,需要檢查應用等待期間由誰保留更新,以及這種等待能夠向上遊傳播多遠。如果 SDK 已經丟棄了更新,僅限制儲存佇列並不能保留每條更新。
缺口之後獲取最新價格,也不同於重建缺口期間發生的決策。如果處理停止時價格經歷了 100 → 101 → 100,僅憑最新價格 100 無法重建中間的
enter 和 exit。如果要求保留每條更新的決策,就必須先恢復所需歷史,才能恢復處理。恢復歷史並不意味著它可用於當前決策
圖 3 中,空間釋放後恢復的是此前停止的輸入處理。在實時交易應用中,除了不丟記錄地處理更新,還需要檢查這些更新是否仍足夠新,能夠用於決策。即使按順序回放舊輸入可以恢復狀態,回放期間達到的
enter 或 exit 條件,也未必能直接用於當前訂單。| 應用需要的資訊 | 從佇列滿或資料缺口恢復時需要定義什麼 |
|---|---|
| 決策需要每個中間狀態轉換 | 恢復必要的歷史和之前的狀態,然後按順序處理。將歷史回放產生的結果是否可以用於下單,與當前決策分開定義 |
| 決策可以從最新狀態開始 | 驗證這一規格,重新同步到一致的最新狀態,再作決策。不要將其視為已經重建中間條件觸發 |
| 當前決策有新鮮度截止要求 | 定義可接受的最大更新年齡和決策截止時間,以及超限後停止決策與恢復的條件 |
增加容量可以保留更多記錄,但也允許舊更新等待更久。除了記錄數量與位元組數,還應檢查最舊的更新已經等待多久。不要在超過截止時間後默默丟棄必需記錄;應將記錄保留與當前決策處理可以執行的條件分開。這個教學示例按順序處理全部六個輸入,沒有實現實時輸入的重新獲取或自動恢復下單。
6. 區分提交成功、儲存完成與關閉
提交成功時,記錄只是交給了寫入器。只有在規定的寫入與同步操作完成後,才能把儲存計為成功。在這個 TypeScript 示例中,每條記錄的完成條件是
writeFile → datasync;在 Rust 驗證中,則是 write_all → flush → sync_data。[S09][S10][S12]Tokio 的
flush 完成進行中的寫入,與請求將作業系統緩衝區同步到裝置的 sync_data 不同。我們可以驗證這些 API 呼叫成功,但這不等於測試了斷電、新建檔案的目錄同步,或故障裝置的恢復。正常關閉會結束新輸入處理、停止進一步提交,並等待寫入器處理完已接受的記錄。使用 Tokio 時,釋放所有傳送控制代碼並等待寫入器的
JoinHandle。在 TypeScript 示例中,呼叫 queue.close(),然後等待 writerTask。如果輸入處理因異常或提前停止而結束,也必須進入這條關閉路徑。[S03][S06]儲存失敗時,區分未寫入記錄與結果未知的記錄
儲存失敗時,寫入器關閉佇列。等待空間的輸入側也會獲知佇列已關閉,並停止後續處理。TypeScript 和 Rust 價格示例在 Report 中保留未寫入、儲存結果未知及未被接受儲存的完整記錄。對於未處理的輸入,Rust 在 Report 中保留完整 Input,而 TypeScript 使用 Report 的 ID 和原始輸入檔案進行追蹤。關閉後,Rust 寫入器還會取出佇列中的剩餘專案,在退出前將其恢復為未寫入記錄。[S06][L03][L06]
配套的 Rust Geyser 回放示例在賬本中保留未完成的 ID 與狀態,並在不可變 protobuf 檔案中保留原始輸入。由於保留方式不同,應檢查報告中的每個 ID 是否都能追溯到原始輸入或記錄。僅僅丟棄接收端控制代碼,不會儲存尚未讀取的載荷。對於實時輸入,應另行設計未儲存載荷的重新獲取或保留方式。[S06][L04]
如果記錄在開始寫入前失敗,就可以確定尚未寫入。但開始寫入後發生錯誤,可能留下部分寫入。如果寫入後無法確認同步,也沒有滿足規定的儲存完成條件。這些示例將此類記錄保留為儲存結果未知,不將其計為成功。
關閉時,將輸入 ID 分類為以下五種狀態。驗證這五個集合互不重疊,並且覆蓋所有原始輸入。
| 關閉時的狀態 | 含義 |
|---|---|
| 儲存完成 | 決策以及規定的寫入、同步操作均已完成 |
| 已接受,未寫入 | 已交給寫入器,但因寫入前失敗或從剩餘佇列恢復而仍未寫入 |
| 已接受,儲存結果未知 | 無法確認規定的儲存完成,例如開始寫入後發生故障 |
| 已決策,未被接受儲存 | 決策已完成,但關閉導致無法交給寫入器 |
| 未處理 | 輸入仍保留著,但尚未應用狀態和處理決策 |
已決策數量不是要在這五個集合之外另加的集合。它統計前四類中已完成決策的輸入。應將其與交給佇列的數量和成功儲存的數量分開檢查。
盲目重試結果未知的追加寫入,可能產生重複記錄或不完整的行。恢復需要使用記錄 ID、目標端事務以及去重約定。這些示例涵蓋停止後識別並報告未完成專案,沒有實現自動重試或崩潰後的恢復。
如果儲存目標不返回,還需要另行決定關閉過程應等待多久。僅寫上
await writerTask 或 task.await,無法解決關閉截止時間或安全取消已開始 I/O 的問題。如有需要,應結合儲存目標的約定,驗證到達截止時間時能夠保留和報告什麼。7. 在實際接收程式碼中找到改進位置
將這種分離引入自己的交易應用時,要從接收更新的函式回溯到呼叫它的程式碼。即使儲存函式包含
await,呼叫方是否等待其完成,也會改變問題本身和需要修復的位置。先檢查以下三項。| 在程式碼中檢查什麼 | 確認後可以考慮的更改 |
|---|---|
| 已經到達的下一條更新,是否必須等待前一次輔助儲存才能作出決策? | 移除決策不需要的儲存等待,並將已經確定的記錄交給獨立寫入器 |
| 下一次決策在推進,但未完成儲存是否持續累積? | 限制併發儲存和等待工作的數量,並決定佇列滿時在哪裡保留輸入 |
| 必需的更新到達儲存佇列前,是否已被接收側丟棄? | 回溯到丟棄分支,重新審視輸入保留、重新獲取,以及出現缺口後恢復決策的條件 |
同樣是“跟不上更新”的症狀,可能需要這些不同的修復。關聯下一條更新的處理開始、儲存開始與完成、排隊工作和被丟棄更新,可以縮小改進位置的範圍。
給 TypeScript 接收示例新增儲存
官方 Solana Stream SDK 的 Geyser 接收示例,也使用佇列將收到的更新交給處理邏輯。在所檢查版本的 TypeScript 示例中,
runHandler 為每條更新呼叫 onUpdate,併為返回的 Promise 附加錯誤處理,但不等待其完成。因此,即使按下面的方式實現儲存,後續更新處理也可能在前一次儲存完成前開始。[S24][S25]以下插入程式碼展示了這個問題。
decideAndSnapshot 是用於說明的函式名,代表現有應用的狀態更新、決策以及已確定記錄的建立。typescript
// この形を登録しただけでは、保存の並行数と順序は決まらない。
onUpdate: async (update) => {
const record = decideAndSnapshot(update);
await saveAuxiliary(record);
}// この形を登録しただけでは、保存の並行数と順序は決まらない。
onUpdate: async (update) => {
const record = decideAndSnapshot(update);
await saveAuxiliary(record);
}如果這裡的未完成儲存不斷累積,就屬於上表的第二種情況。有限的接收佇列,並不限制專案取出後產生的 Promise 或儲存操作。這個示例的
processedUpdates 也不能用作已完成儲存的數量。[S24]在這種情況下,可以考慮讓一個決策任務按順序建立已經確定的記錄,並交給有界儲存路徑。如果只是把第 3 節的
await queue.put(...) 放入每個回撥,佇列滿時也會為每條更新產生更多等待中的回撥。應在負責交接輸入的位置,阻止繼續處理下一條輸入,直到當前記錄被接受,並檢查在此期間接收側哪裡可以保留輸入。在所檢查的 TypeScript 示例中,
processEvents 內的 eventQueue.shift() 取出更新,然後依次傳給 processEvent、runHandler 和 onUpdate。在自己的實現中,找到負責將下一條更新交給處理過程的對應位置。還要檢查等待儲存路徑接受記錄的 Promise 是否返回給呼叫方,使等待能夠反向傳播到取出更新的元件。如果將該元件改為等待儲存接受,更新就會累積在它前面的 SDK 佇列中。除了儲存函式本身,還要處理停止出隊位置上游的保留問題。[S24]例如,若已確認上游能夠保留尚未取出的更新,而且單個處理任務可以在獲取下一條更新前等待,就按以下順序推進。這是定位修改點的步驟,並不是用於替換某個 SDK 專用 API 的完整程式碼。
- 輸入任務取出下一條更新。
- 更新狀態、檢查條件,並確定該時刻的記錄。
- 保留當前記錄,直到儲存路徑接受它。不要為每條更新建立更多等待任務。
- 接受後,再繼續下一次獲取。關閉時,恢復未被接受的記錄,停止後續輸入,並檢查寫入器的關閉結果。
利用 SDK 和提供方的約定,確定此任務等待期間更新會發生什麼。
| 已確認的接收側條件 | 連線前必須確定的內容 |
|---|---|
| 可以等待再取下一條更新,上游也能保留必需更新 | 將等待集中到一個出隊任務。還要檢查上游緩衝區的數量與位元組上限,以及滿時的行為 |
| 回撥無法停止,但所需歷史可以重新獲取 | 保留捕獲位置、缺失範圍和之前的狀態,建立從停止決策、恢復歷史到恢復執行的路徑 |
| 回撥無法停止,且所需歷史無法恢復 | 當前連線不滿足保留每條更新的條件。重新審視訂閱範圍、輸入保留方式和接收側容量 |
不要假設 SDK 支援暫停或重新獲取歷史。不僅要檢查是否存在 API,還要檢查停止期間更新保留在哪裡,以及所需範圍是否能夠恢復。如果規格允許重新同步到最新狀態,應按第 5 節中的另一種條件處理,不要將其等同於保留每條更新。
這項更改旨在控制未完成工作和儲存順序。將儲存改為逐條執行,會改變原本已併發執行的 I/O 的效能,因此需要重新測量決策延遲與儲存吞吐量。
此外,所檢查版本的 Rust 和 TypeScript 示例都存在一條路徑,在內部佇列滿時丟棄普通更新。在下游新增儲存佇列,無法恢復上游已經丟失的更新。如果決策還需要中間更新,設計中就必須包含佇列滿時的保留與重新獲取。這是所引用示例的行為,不是所有 Geyser 客戶端共有的限制。[S24][S25]
對於實時輸入,需要檢查停止期間由誰保留更新,以及處理可以從哪裡恢復。與輸入檔案始終可用的教學示例不同,僅停止迴圈不一定能保留未處理更新。如果無法恢復所需歷史,應區分回到最新狀態和重建缺失區間內的決策。
所引用示例的版本、函式對映及佇列滿分支,記錄在原始碼檢查說明和來源 [S24][S25] 中。檢查自己版本的呼叫模式,判斷是否適用相同模式。
將價格示例適配為 Geyser 格式更新
到目前為止,分離的是有序輸入處理與其固定結果的儲存。配套的 Rust 回放示例解碼保留在檔案中的 Geyser 格式交易更新,並提取對指定程式的呼叫。其計算內容與價格條件檢查不同,但關係相同:一個輸入任務確定結果,再交給一個寫入器。[L04]
| 角色 | 六個價格的示例 | Geyser 格式回放示例 |
|---|---|---|
| 輸入 | 帶 ID 的價格更新 | 儲存在檔案中的 protobuf 更新 |
| 輸入側工作 | 應用價格並確定決策 | 解碼更新並提取程式呼叫 |
| 交給儲存的內容 | 該更新的價格與決策結果 | 從該更新提取的結果 |
| 儲存順序 | 按輸入順序逐條儲存 | 按輸入順序逐條儲存 |
| 受限內容 | 最多六個輸入,以及容量為 2 的小記錄佇列 | 除佇列記錄數外,還限制交接的變長位元組總量 |
Geyser 回放示例的更改前後版本也使用相同的
process_update、encode_result 和 save。它們先使用 try_reserve 預留一個佇列槽位;如果佇列滿,則呼叫 reserve().await,同時輸入側繼續持有當前位元組。獲得槽位後,slot.send(Pending { ... }) 轉移所有權。值的交接時機與價格示例的 try_send 不同,但兩者都在接受前持續追蹤當前專案,不會提前繼續後續輸入。[S04][S05][L04]變長記錄需要獨立於記錄數量的位元組上限。此回放示例的驗證設定為佇列容量 64 條記錄,以及由 Semaphore 實施的 1 MiB 位元組預算。預算涵蓋獲取許可後輸入側當前記錄、佇列中的記錄和正在儲存的記錄。
Pending 持有許可,處理後釋放許可便歸還容量。如果單條記錄超過上限,示例會返回錯誤,而不是永遠等待空間。[S30][L04]這 1 MiB 不是整個程序的記憶體上限。獲取位元組容量前的當前記錄、已解碼輸入、原始測試資料和賬本分別消耗記憶體。無論 64 條記錄還是 1 MiB,都不是應該直接用於生產環境的數值。應根據實際輸入大小、可接受積壓和儲存能力進行選擇。[L04]
此回放示例是用於檢查這些邊界如何在本地輸入下工作的應用型教學材料。它不是能夠直接接入實時 SDK 回撥的完整介面卡。請根據自己的接收路徑,實現前面檢查過的呼叫模式、上游保留方式及缺口後的恢復條件。
8. 用少量輸入檢查處理順序與保留情況
重構設計後,先驗證相同輸入仍然產生相同的決策和儲存記錄。即使分離儲存讓下一次決策更早推進,決策順序或儲存內容的改變也會違背預期更改的目的。少量輸入便於將每條記錄追蹤到底。
為順序版本和分離版本提供相同的六個輸入
為 TypeScript 和 Rust 價格示例提供相同的六個輸入:100 → 101 → 102 → 100 → 101 → 99。在每種語言內部,順序版本和分離版本使用相同的決策函式、JSON 編碼與儲存函式。預期決策為
hold → enter → hold → exit → enter → exit。[L03][L06]bash
node example.ts --mode before --out run-before
node example.ts --mode after --capacity 2 --out run-after
node --test checks/example.test.mjsnode example.ts --mode before --out run-before
node example.ts --mode after --capacity 2 --out run-after
node --test checks/example.test.mjs在
records.jsonl 中檢查儲存內容與順序,在 report.json 中檢查決策、儲存、未完成 ID 和執行順序。已驗證正常完成時,兩種方式都按相同順序對全部六個輸入作出決策並儲存,JSONL 的每個位元組都一致。示例不建立外部連線,使用真實檔案寫入與 datasync()。[L03]在同一個 ZIP 的
price-rust 目錄內執行 Rust 版本。另見相同六個價格的執行說明。該版本已在 release 構建中驗證,使用 Rust 1.100.0、Tokio 1.54.1,以及由 Cargo.lock 固定的依賴項。[L06]bash
cargo build --release --locked
cargo run --release --locked -- before out/before
cargo run --release --locked -- after out/after
cargo test --release --lockedcargo build --release --locked
cargo run --release --locked -- before out/before
cargo run --release --locked -- after out/after
cargo test --release --locked對於 Rust,也應檢查每個輸出目錄中的
records.jsonl 和 report.json。順序版本和分離版本的六個輸入決策、儲存順序以及 JSONL 的每個位元組都一致。兩種語言得到相同的預期值,驗證了教學示例執行相同工作。這裡不比較處理時間,也不比較語言速度排名。再次執行時,請使用新的輸出目錄。[L06]填滿佇列,檢視當前記錄保留在哪裡
佇列滿測試使用一個需要手動釋放寫入器的門控。與第 5 節圖 3 一樣,它在 ID 0 開始寫入前停止寫入器,將 ID 1 和 2 放入佇列,並讓 ID 3 留在輸入側。測試驗證處理不會繼續到 ID 4,並且寫入器恢復後,輸入側能夠交出保留的 ID 3 並繼續。
這驗證了只要還有容量,即使寫入器暫停,決策也能推進;容量用盡後,輸入側保留當前記錄並等待。無需比較耗時,就能檢查分離與 Full 處理。
Rust 的 Full 測試在
report.json 中記錄以下觀察。這是從 full 陣列中提取的一項。[L06]json
{"current_seq":3,"decided_count":4,"accepted_count":3,"queue_depth":2}{"current_seq":3,"decided_count":4,"accepted_count":3,"queue_depth":2}截至 ID 3,已有四個輸入完成決策;ID 0–2 這三個已被接受;ID 1 和 2 這兩個位於佇列中。掛起的傳送持有當前的 ID 3。儲存完成在
writes.saved 中單獨檢查。門控釋放、處理正常結束後的報告中,ID 0–5 按順序出現在該欄位中。此次執行的 full 陣列開頭還包含 ID 2 的一次觀察。由於測試會等到 current_seq 等於 3 的觀察後才恢復儲存,不要將第一項讀成 ID 3 時的狀態。[L06]| 要測試的場景 | 需要驗證的行為 |
|---|---|
| 正常完成 | 對全部原始輸入按相同順序決策,並儲存相同記錄 |
| 佇列滿 | 保留當前記錄,不繼續下一條輸入,空間釋放後交出同一條記錄 |
| 寫入器關閉 | 保留未被接受的記錄或其恢復來源與 ID,並停止後續輸入 |
| 儲存前失敗 | 區分尚未寫入的記錄和尚未決策的輸入 |
| 寫入後、確認同步前失敗 | 保留未知結果,不計為儲存完成 |
| 提前停止或輸入處理異常 | 進入關閉流程,處理完已接受的記錄,並檢查寫入器結果 |
在每種情況下,都要檢查第 6 節的五種狀態是否無重疊地覆蓋全部原始輸入。這能避免因為丟失必要工作而顯得更快的更改。TypeScript 價格示例檢查了表中的每個場景。Rust 價格示例使用六項功能檢查,驗證正常完成、從 Full 恢復、Closed、儲存前和寫入後失敗,以及在三條記錄之後停止輸入。輸入處理異常或 panic 的恢復,不在這個 Rust 價格示例的驗證範圍內。[L03][L06]
配套的 Geyser 回放示例使用明確標明為合成的 protobuf 輸入,檢查提取結果、儲存內容、順序、數量與位元組上限、故障和停止。其輸入與工作內容,和驗證價格決策的新示例是區分開的。[L04]
在自己的實現中驗證等待是否減少
應用這項設計時,使用第 1 節的測量點,檢查下一次決策能否不等前一次儲存完成就開始。更改前後使用相同的輸入、決策和儲存條件,並將決策完成與全部儲存完成分開檢查。把交接成本和佇列滿等待納入其中,才能確定自己實現中哪些等待減少了、哪些仍然存在。
原始執行記錄、故障情況下的數量、構建條件和補充測量方法說明,彙總在驗證說明中。正文圖示是用於追蹤依賴關係的解釋模型;其中假設的時間不是真實環境中的改善測量。
9. 找出下一處等待,在併發與並行之間選擇
分離儲存等待,不會消除接收後的所有延遲。重新測量解碼、狀態更新、條件檢查、儲存資料準備、佇列和鎖,找到下一個耗時位置。同時檢查,將操作移入另一個任務後,交接或同步等待是否增加。
併發可以在 I/O 等待期間推進其他工作;本文的寫入器就是一個例子。對於長時間佔用 CPU 的工作,應考慮減少計算或在獨立執行資源上執行。Tokio 的
spawn 不會為每個任務建立專用執行緒,僅新增 async 也不會把繁重計算移到另一個 CPU。[S03][S07][S08]例如,在另一個 CPU 上準備或壓縮大量資料時,要定義在保留輸入的同時允許交接多少資料、worker 數量和佇列上限。選擇 Tokio 的
spawn_blocking 或 CPU 工作執行資源時,不僅要限制執行中操作的數量,還要限制等待啟動的工作。不要假設已經開始的阻塞操作可以輕易取消。[S07]依賴前一次更新結果的狀態更新和條件檢查,仍必須保持順序。即使獨立計算並行執行,也要定義結果的應用順序、過時結果的處理方式,以及缺失輸入後的重新同步。決策前必需的儲存,其依賴不能移除。應檢查在保留必要依賴的前提下等待是否減少,而不只是看啟動的操作是否更多。
Node.js 工作執行緒和獨立的 Python 程序同樣可以分離 CPU 工作。比較時應包含傳遞資料的轉換與複製、佇列等待和結果返回時間。還應分別檢查所使用的 Python 構建、GIL 和擴充套件模組帶來的條件。[S13][S16][S17]
對於新的低延遲接收與決策引擎,Rust 是首選。在現有 TypeScript 或 Python 應用中,一種做法是保留 UI、配置、監控和研究工作,只將測量表明確有需要的部分提取到 Rust。要將設計更改帶來的改善,與遷移後實現的差異分開,並使用相同輸入、工作和正確性要求進行比較。驗證分離 I/O 儲存,不能證明 CPU 並行化的收益。請用實際將使用的載荷和處理進行檢查。
10. 附錄:使用 AI 智慧體診斷和改進程式碼
這兩個提示詞可以分別獨立交給能夠讀取您倉庫的 AI。第一個涵蓋等待診斷、最小更改和相同條件下的比較;第二個涵蓋佇列滿、故障和關閉。延續既有許可權與工作規則,並根據哪些等待減少了,以及順序和記錄是否得到保留,來評估建議的更改。
1. 診斷接收後的等待,並實現必要的分離
text
Investigate the path in this repository from receiving an update through state updates and decision processing. Identify where waiting for saving or data preparation to finish delays the next update, or where unfinished auxiliary work keeps accumulating. Carry the work through to an evidence-based minimal fix and a before/after comparison under the same conditions.
First check the existing working rules, permissions, uncommitted changes, and versions of the language, runtime, SDK, and dependencies. Do not overwrite other changes. Production changes, load tests against external services, transaction submission, and paid contracts are outside scope. Proceed with the necessary local investigation, modifications, and small replay checks. Do not output private keys, credentials, or customer data.
1. Trace the actual files and functions for reception, decoding, state updates, decisions, and saving, including their callers. Check whether callers wait for the Promise/Future returned by an async function, invoke it independently for each event, and when they take items from intervening queues. Do not infer from the name async alone that the next reception is blocked or that the work runs on another thread. Also check whether the SDK's processed count includes save completion and whether its default full-queue handling discards updates.
2. Distinguish I/O waits, CPU occupancy, queue waits, and lock waits, and separate confirmed facts, hypotheses about causes, and unmeasured areas. Use consumers, recovery processing, README files, specifications, and existing tests to classify records that must be durable before a decision versus auxiliary records that may be saved later. If the required update order, stopping decisions and resynchronizing after gaps, or the save-failure contract is unclear, investigate the evidence without removing the dependency. Also investigate the maximum acceptable update age, decision deadlines, and the conditions for resuming current decisions after history recovery. If these are undefined, report them as undefined rather than inventing values.
3. Before making changes, fix the finite input and expected correctness results. Distinguish input captured from a real stream from input created for illustration, and record the input hash, count, order, and capture range. Do not call the entry point where an SDK delivers decoded values a wire-reception timestamp, or call re-encoded values the original wire bytes. Where usable input or an execution environment is unavailable, do not label an unexecuted check as a completed measurement.
4. Define measurement start and end points. Using the monotonic clock of the same process, distinguish the handoff/replay schedule, decision start and completion, save acceptance, and save start and completion. If reproducing arrival intervals, do not delay the schedule to match completion of the previous save. If measuring a finite sequence with all inputs ready at the start, state that condition and do not call it latency from actual reception. Do not draw conclusions about a language's computation speed from numbers that mix timer-resumption time, actual processing, and real I/O. Accompany p50/p95/p99 with sample counts and calculation methods, and reconcile processed, unprocessed, discarded, duplicate, and save-unconfirmed IDs, decision results, order, and saved contents. The denominator for the fraction completed within the deadline is all target inputs. For queue counts, bytes, the oldest wait, CPU, and memory, distinguish what was verified from what was not measured.
5. First make the minimal fix in the existing environment for the confirmed cause. If separating auxiliary work, define ownership of immutable records, a single updater of mutable state, a bounded queue, and the number of writers. send().await waits when full. For Full from a nonblocking submission, use the contract to decide whether to retain the returned record and wait or stop, and report either the waiting time or the unprocessed range. For Closed, retain the unaccepted record and handle stopping and recovery. Also check upstream retention. Distinguish successful submission from save completion, and write completion from sync/commit. Submission failure after a decision is “decided, not accepted for saving”; do not count it as unprocessed input. Do not make a change appear faster by using an unbounded queue, a waiting task per update, or discarding required updates.
6. Compare before and after using the same input, arrival conditions, work, correctness requirements, and save-completion conditions. Test normal operation, a short burst, a full queue, save failure, writer closure, and draining on normal shutdown; reconcile the location and order of every input. Check whether shutdown handling is reached even on an input exception or early return, and retain unknown save outcomes as unknown. Also report conditions under which there is no improvement.
7. If costs remain after improving the existing environment and the requirements justify it, evaluate extracting the low-latency reception and decision processing into Rust. Specify the target processing and costs of copying, allocation, sharing, synchronization, and boundary crossings. Record the release build and dependency lock, runtime, and SDK/native layers, and compare under the same conditions. Arc provides shared ownership, Send/Sync are type properties, and Tokio is the execution runtime. Arc alone does not guarantee safe concurrent mutation of inner values or zero-copy. Do not conclude that a complete migration is needed or rank languages by speed without measurement evidence.
Finally, report the diagnostic evidence, modified files and functions, reproduction commands, before/after results, correctness and retention checks, unmeasured scope, and the specific problems that remain. Do not unnecessarily change areas that have no problem or are already separated. If the evidence does not support an article's or proposal's central claim, do not treat it as complete merely by adding limitations; explicitly state whether that claim is retained or rejected and which work remains unfinished.Investigate the path in this repository from receiving an update through state updates and decision processing. Identify where waiting for saving or data preparation to finish delays the next update, or where unfinished auxiliary work keeps accumulating. Carry the work through to an evidence-based minimal fix and a before/after comparison under the same conditions.
First check the existing working rules, permissions, uncommitted changes, and versions of the language, runtime, SDK, and dependencies. Do not overwrite other changes. Production changes, load tests against external services, transaction submission, and paid contracts are outside scope. Proceed with the necessary local investigation, modifications, and small replay checks. Do not output private keys, credentials, or customer data.
1. Trace the actual files and functions for reception, decoding, state updates, decisions, and saving, including their callers. Check whether callers wait for the Promise/Future returned by an async function, invoke it independently for each event, and when they take items from intervening queues. Do not infer from the name async alone that the next reception is blocked or that the work runs on another thread. Also check whether the SDK's processed count includes save completion and whether its default full-queue handling discards updates.
2. Distinguish I/O waits, CPU occupancy, queue waits, and lock waits, and separate confirmed facts, hypotheses about causes, and unmeasured areas. Use consumers, recovery processing, README files, specifications, and existing tests to classify records that must be durable before a decision versus auxiliary records that may be saved later. If the required update order, stopping decisions and resynchronizing after gaps, or the save-failure contract is unclear, investigate the evidence without removing the dependency. Also investigate the maximum acceptable update age, decision deadlines, and the conditions for resuming current decisions after history recovery. If these are undefined, report them as undefined rather than inventing values.
3. Before making changes, fix the finite input and expected correctness results. Distinguish input captured from a real stream from input created for illustration, and record the input hash, count, order, and capture range. Do not call the entry point where an SDK delivers decoded values a wire-reception timestamp, or call re-encoded values the original wire bytes. Where usable input or an execution environment is unavailable, do not label an unexecuted check as a completed measurement.
4. Define measurement start and end points. Using the monotonic clock of the same process, distinguish the handoff/replay schedule, decision start and completion, save acceptance, and save start and completion. If reproducing arrival intervals, do not delay the schedule to match completion of the previous save. If measuring a finite sequence with all inputs ready at the start, state that condition and do not call it latency from actual reception. Do not draw conclusions about a language's computation speed from numbers that mix timer-resumption time, actual processing, and real I/O. Accompany p50/p95/p99 with sample counts and calculation methods, and reconcile processed, unprocessed, discarded, duplicate, and save-unconfirmed IDs, decision results, order, and saved contents. The denominator for the fraction completed within the deadline is all target inputs. For queue counts, bytes, the oldest wait, CPU, and memory, distinguish what was verified from what was not measured.
5. First make the minimal fix in the existing environment for the confirmed cause. If separating auxiliary work, define ownership of immutable records, a single updater of mutable state, a bounded queue, and the number of writers. send().await waits when full. For Full from a nonblocking submission, use the contract to decide whether to retain the returned record and wait or stop, and report either the waiting time or the unprocessed range. For Closed, retain the unaccepted record and handle stopping and recovery. Also check upstream retention. Distinguish successful submission from save completion, and write completion from sync/commit. Submission failure after a decision is “decided, not accepted for saving”; do not count it as unprocessed input. Do not make a change appear faster by using an unbounded queue, a waiting task per update, or discarding required updates.
6. Compare before and after using the same input, arrival conditions, work, correctness requirements, and save-completion conditions. Test normal operation, a short burst, a full queue, save failure, writer closure, and draining on normal shutdown; reconcile the location and order of every input. Check whether shutdown handling is reached even on an input exception or early return, and retain unknown save outcomes as unknown. Also report conditions under which there is no improvement.
7. If costs remain after improving the existing environment and the requirements justify it, evaluate extracting the low-latency reception and decision processing into Rust. Specify the target processing and costs of copying, allocation, sharing, synchronization, and boundary crossings. Record the release build and dependency lock, runtime, and SDK/native layers, and compare under the same conditions. Arc provides shared ownership, Send/Sync are type properties, and Tokio is the execution runtime. Arc alone does not guarantee safe concurrent mutation of inner values or zero-copy. Do not conclude that a complete migration is needed or rank languages by speed without measurement evidence.
Finally, report the diagnostic evidence, modified files and functions, reproduction commands, before/after results, correctness and retention checks, unmeasured scope, and the specific problems that remain. Do not unnecessarily change areas that have no problem or are already separated. If the evidence does not support an article's or proposal's central claim, do not treat it as complete merely by adding limitations; explicitly state whether that claim is retained or rejected and which work remains unfinished.2. 檢查佇列滿、故障和關閉期間,更新與記錄是否始終可核對
text
Examine the separation of reception and decision processing from auxiliary saving in this repository, and verify that updates and records remain accounted for when the queue is full, saving fails, the writer closes, or processing ends normally. Make minimal fixes only for defects supported by evidence, and verify before and after using the same small local input.
Check the existing working rules, permissions, uncommitted changes, and versions of the language, runtime, SDK, and dependencies. Do not overwrite other changes, and limit modifications to the retention and shutdown conditions in this task. Production changes, load tests against external services, transaction submission, and paid contracts are outside scope. Proceed with the necessary local investigation, modifications, and replay checks. Do not output private keys, credentials, or customer data.
1. Identify the actual files and functions, the owner of received input, the updater of mutable state, queue capacity and the per-record byte limit, the number of writers, retries, and shutdown paths. Also investigate whether SDK callbacks wait for async processing to finish, whether processed counts mean save completion, and whether an upstream queue discards items when full. Separate confirmed facts, hypotheses, and unmeasured areas. If saving before a decision is required, preserve that dependency and do not treat the record as auxiliary.
2. Classify the same input IDs as unprocessed; decided, not accepted for saving; accepted, not written; accepted, save outcome unknown; or save complete. Verify that these five sets are disjoint and cover all input, and detect discards, duplicates, order violations, and double-counting. Do not arbitrarily classify records with unknown outcomes, such as partial writes, as successful or unwritten. Do not add the decided count on top of the five sets. Local sequence numbers assigned to a real stream identify the captured sequence; they are not proof that every server update was captured. Record disconnected, retransmitted, and uncaptured ranges separately.
3. For nonblocking submission, trace where values returned by Full/Closed go. If send().await or reserve().await is used, check whether that wait stops the next update. Also check for unbounded waiting in Promises or tasks after leaving the queue, and in retry destinations. Do not assume that finite memory can handle sustained overload without loss or stopping.
4. Before making changes, use finite input to reproduce normal operation, a short burst, insufficient capacity, save failure, a channel closed by the saving side, and a normal stop partway through input. Do not treat successful submission as save completion. Check that acceptance stops after failure, accepted items are drained or recovered, all send handles are released, the save task's result is checked, and flush/sync/commit conditions are met. Check whether shutdown handling runs even on an input exception or early return. Retain records with unknown outcomes, such as partial writes, as unknown.
5. Check what stopping can preserve. Retaining a local input file differs from requesting retransmission or retention of live input. State which input ID and which preceding state processing will resume from. Do not treat SDK pausing or history refetching as available without verification. Do not assume that the latest state alone can reconstruct conditions reached during a gap. Separate state recovery through historical replay from the conditions that permit current decisions to resume, and report freshness or deadline requirements as unknown if they are unknown. Do not unconditionally retry appends whose saving is unconfirmed and thereby create more duplicates or incomplete lines.
6. Implement the necessary minimal fix and rerun under the same conditions. Compare counts and IDs for processed, unprocessed, discarded, save-unconfirmed, and duplicate inputs, as well as decision results, save order, completion criteria, and exit codes. Avoid parallel saving that breaks required order or changes that discard unsaved records to finish. Report queue counts, bytes, the oldest wait, latency, CPU, and memory only where measured. Explicitly state if panic, process crash, forced termination, power loss, or shutdown deadlines have not been tested.
Finally, report the confirmed problems and evidence, minimal fixes, reproduction commands, whether every input is accounted for consistently in each scenario, and the remaining failure scope. Do not change areas that already meet the requirements. Zero locally discarded items alone does not guarantee that all items were saved, crash durability, gap-free reception of a real stream, or production correctness.Examine the separation of reception and decision processing from auxiliary saving in this repository, and verify that updates and records remain accounted for when the queue is full, saving fails, the writer closes, or processing ends normally. Make minimal fixes only for defects supported by evidence, and verify before and after using the same small local input.
Check the existing working rules, permissions, uncommitted changes, and versions of the language, runtime, SDK, and dependencies. Do not overwrite other changes, and limit modifications to the retention and shutdown conditions in this task. Production changes, load tests against external services, transaction submission, and paid contracts are outside scope. Proceed with the necessary local investigation, modifications, and replay checks. Do not output private keys, credentials, or customer data.
1. Identify the actual files and functions, the owner of received input, the updater of mutable state, queue capacity and the per-record byte limit, the number of writers, retries, and shutdown paths. Also investigate whether SDK callbacks wait for async processing to finish, whether processed counts mean save completion, and whether an upstream queue discards items when full. Separate confirmed facts, hypotheses, and unmeasured areas. If saving before a decision is required, preserve that dependency and do not treat the record as auxiliary.
2. Classify the same input IDs as unprocessed; decided, not accepted for saving; accepted, not written; accepted, save outcome unknown; or save complete. Verify that these five sets are disjoint and cover all input, and detect discards, duplicates, order violations, and double-counting. Do not arbitrarily classify records with unknown outcomes, such as partial writes, as successful or unwritten. Do not add the decided count on top of the five sets. Local sequence numbers assigned to a real stream identify the captured sequence; they are not proof that every server update was captured. Record disconnected, retransmitted, and uncaptured ranges separately.
3. For nonblocking submission, trace where values returned by Full/Closed go. If send().await or reserve().await is used, check whether that wait stops the next update. Also check for unbounded waiting in Promises or tasks after leaving the queue, and in retry destinations. Do not assume that finite memory can handle sustained overload without loss or stopping.
4. Before making changes, use finite input to reproduce normal operation, a short burst, insufficient capacity, save failure, a channel closed by the saving side, and a normal stop partway through input. Do not treat successful submission as save completion. Check that acceptance stops after failure, accepted items are drained or recovered, all send handles are released, the save task's result is checked, and flush/sync/commit conditions are met. Check whether shutdown handling runs even on an input exception or early return. Retain records with unknown outcomes, such as partial writes, as unknown.
5. Check what stopping can preserve. Retaining a local input file differs from requesting retransmission or retention of live input. State which input ID and which preceding state processing will resume from. Do not treat SDK pausing or history refetching as available without verification. Do not assume that the latest state alone can reconstruct conditions reached during a gap. Separate state recovery through historical replay from the conditions that permit current decisions to resume, and report freshness or deadline requirements as unknown if they are unknown. Do not unconditionally retry appends whose saving is unconfirmed and thereby create more duplicates or incomplete lines.
6. Implement the necessary minimal fix and rerun under the same conditions. Compare counts and IDs for processed, unprocessed, discarded, save-unconfirmed, and duplicate inputs, as well as decision results, save order, completion criteria, and exit codes. Avoid parallel saving that breaks required order or changes that discard unsaved records to finish. Report queue counts, bytes, the oldest wait, latency, CPU, and memory only where measured. Explicitly state if panic, process crash, forced termination, power loss, or shutdown deadlines have not been tested.
Finally, report the confirmed problems and evidence, minimal fixes, reproduction commands, whether every input is accounted for consistently in each scenario, and the remaining failure scope. Do not change areas that already meet the requirements. Zero locally discarded items alone does not guarantee that all items were saved, crash durability, gap-free reception of a real stream, or production correctness.這裡釋出的兩個提示詞的日文原版,均由與實現者不同的 AI 完整複製,並在獨立本地副本中分別應用於 TypeScript 示例和 Rust 價格示例。每份副本的試驗都檢查了八項 TypeScript 功能測試和 release 構建中的六項 Rust 功能測試,以及順序、分離 CLI 和故障場景。目標檔案、原因診斷、復現命令、原始提示詞的雜湊和結果,記錄在等待診斷與分離試驗以及 Full、故障與關閉試驗中。
對於已經滿足要求的分離版本,沒有作出不必要的更改。此教學材料沒有定義可接受的資料年齡、決策截止時間,或恢復歷史後重新開始當前決策的條件。依照提示詞,試驗將這些事項報告為未定義、未驗證,而沒有自行編造數值。本地回放中的保留檢查,並不能證明已驗證生產決策恢復或真實 Geyser 效能。
這些 AI 試驗檢查的是提示詞的具體程度,以及與文章的一致性。它們不同於證明真實讀者理解程度、滿意度、再次閱讀意願,或在未知倉庫中成功率的研究。
11. 將高速資料轉化為快速響應
即使資料流很快,接收後累積的不必要等待,仍會延遲資料到達決策邏輯。檢查實現中在等待什麼、哪些順序是必要的,再只分離能夠獨立推進的工作。分離儲存後,繼續測量 CPU 工作、共享狀態和佇列等待,逐一細化必要邊界。
應用內部等待減少後,將接收前的資料新鮮度、RPC 或流訪問、網路路徑和執行位置作為獨立階段進行檢查。定義所需響應時間、輸入量以及停止和恢復條件,然後使用實際會採用的協議、地區、時段和負載比較 ERPC 環境。選擇高速資料和高效使用它的實現,以滿足同一組要求。
參考資料與可執行材料
-
[S01]
Arc::clone新增一個共享同一堆記憶體分配的所有者,不會深複製內容。原子引用計數操作有成本,僅靠 Arc 也不能讓內部值的併發修改變得安全。https://doc.rust-lang.org/std/sync/struct.Arc.html -
[S02]
Send是允許值的所有權線上程之間移動的屬性;Sync允許跨執行緒使用共享引用。它們本身不是執行器、鎖或順序保證。https://doc.rust-lang.org/book/ch16-04-extensible-concurrency-sync-and-send.html -
[S03]
tokio::spawn向執行器註冊非同步任務。普通 spawn 要求 future 及其輸出滿足 Send 和 static 約束,執行位置取決於執行時配置。執行時關閉時,不保證未完成任務能夠執行至完成。https://docs.rs/tokio/1.54.1/tokio/task/fn.spawn.html 區分併發與並行,以及在單執行緒上執行任務:https://tokio.rs/tokio/tutorial/spawning -
[S04] 有界 Sender 的
send().await會等待容量。try_send在佇列滿或接收端關閉時返回。傳送成功不意味著已接收或儲存完成。https://docs.rs/tokio/1.54.1/tokio/sync/mpsc/struct.Sender.html -
[S05]
TrySendError::Full(T)和Closed(T)返回未傳送的值。忽略該值而不恢復,可能丟失必需記錄。https://docs.rs/tokio/1.54.1/tokio/sync/mpsc/error/enum.TrySendError.html -
[S06] 所有 Sender 都被丟棄且剩餘佇列被處理完後,recv 返回 None。丟棄 Receiver 也會丟棄未讀取的值。接收端也可以先關閉,再處理完剩餘內容。https://docs.rs/tokio/1.54.1/tokio/sync/mpsc/index.html
-
[S07]
spawn_blocking將執行移到阻塞池。CPU 工作需要併發上限,達到上限後工作會排隊。對已經開始工作的中止,不能與中止普通非同步任務同等處理。https://docs.rs/tokio/1.54.1/tokio/task/fn.spawn_blocking.html -
[S08] 可以選擇
current_thread或multi_thread。worker_threads設定多執行緒執行時的 worker 數量,並不表示將 worker 繫結到 CPU 核心。https://docs.rs/tokio/1.54.1/tokio/runtime/struct.Builder.html -
[S09] Tokio File 的 flush 完成尚未結束的寫入,這與保證作業系統緩衝區已持久化到裝置不同。sync_all/sync_data 是獨立操作。https://docs.rs/tokio/1.54.1/tokio/fs/struct.File.html
-
[S10] write_all 和 flush 是不同的 AsyncWriteExt 方法。不要省略錯誤與取消處理。https://docs.rs/tokio/1.54.1/tokio/io/trait.AsyncWriteExt.html
-
[S11] Tokio 中的共享狀態可以透過短時間持鎖,或由擁有狀態的任務配合訊息傳遞來處理。應考慮不跨越 await 持鎖的設計。https://tokio.rs/tokio/tutorial/shared-state
-
[S12] Node 的非同步 fs API 在事件迴圈之外執行,但不保證對同一檔案的多次修改自動有序。應避免不等待而使寫入重疊的更改。sync 是單獨的持久化請求。https://nodejs.org/api/fs.html
-
[S13] Node worker_threads 可以並行執行 JavaScript CPU 工作。內建非同步 I/O 適合 I/O,CPU 工作通常也透過 worker 池進行控制。https://nodejs.org/api/worker_threads.html
-
[S14] 在 Node 中,應區分長時間佔用 CPU 的工作與非同步 I/O 等待。https://nodejs.org/learn/asynchronous-work/dont-block-the-event-loop
-
[S15] Python asyncio.Queue(maxsize>0) 設定容量;佇列滿時 put 等待,put_nowait 丟擲 QueueFull。asyncio.Queue 不是執行緒安全的。https://docs.python.org/3/library/asyncio-queue.html
-
[S16] Python 也透過 asyncio 任務支援併發。to_thread 的 CPU 並行能力取決於 GIL、實現和擴充套件模組。https://docs.python.org/3/library/asyncio-task.html
-
[S17] Python 提供執行緒、直譯器和程序執行器。應將 worker 數量與等待執行的工作量分別控制。https://docs.python.org/3/library/concurrent.futures.html
-
[S21] Node EventEmitter 的監聽器呼叫,以及非同步監聽器的 Promise 與拒絕處理。事件發出和監聽器返回的 Promise 完成,是分別處理的。https://nodejs.org/api/events.html
-
[S22] Rust 所有權和向函式傳值。非 Copy 值移動後,原始變數不能繼續作為其所有者使用。呼叫方可以接收返回值。https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html
-
[S24] Solana Stream SDK 的 TypeScript Geyser 執行器:
runHandler不等待 Promise;佇列滿時的丟棄,以及記錄已處理數量的位置。原始碼檢查固定到某個提交。https://github.com/ValidatorsDAO/solana-stream/blob/3b22307033ec6d7b78242d3b4cc9f3168209dcfd/client/geyser-ts/src/lib/geyserRunner.ts -
[S25] 同一 SDK 的 Rust Geyser 執行器:
stream.next()接收入口、try_send、在 Full 時丟棄 Update,以及斷開連線事件處理。https://github.com/ValidatorsDAO/solana-stream/blob/3b22307033ec6d7b78242d3b4cc9f3168209dcfd/client/geyser-rs/src/runtime/runner.rs -
SDK 原始碼審計與測量邊界:sdk-stream-entry-audit.md。
-
[S30] Tokio Semaphore:獲取與釋放容量、自有許可,以及關閉時喚醒等待方。應區分 Arc 的共享所有權與同步機制。https://docs.rs/tokio/1.54.1/tokio/sync/struct.Semaphore.html
-
[L04] 完整 Rust Geyser 回放示例與功能檢查:src/replay.rs、執行說明,以及功能檢查記錄。合成輸入驗證所有權交接、處理結果、順序、Full、故障和關閉。詳細驗證條件見驗證說明。
-
[S34] 等待 JoinHandle 會返回任務輸出或 JoinError。僅丟棄控制代碼會使任務脫離管理,並不確認完成。https://docs.rs/tokio/1.54.1/tokio/task/struct.JoinHandle.html
-
Validators DAO 官方 Discord:https://discord.gg/C7ZQSrCkYR
-
一手來源對映:技術來源與已驗證要點












