快轉到主要內容
  1. Note/

MacOS 上的 Push-based CLI 工作流

·2 分鐘· ·
Blog Zh-Tw
Liu Zhe You
作者
Liu Zhe You
涉略全端、DevOps,目前專注在 Backend
目錄

MacOS 上的 Push-based CLI 工作流
#

System Design 中的 Push-based v.s. Pull-based
#

在系統設計中如果要觀測資料狀態
如:某個 entity 的狀態是否被更新、某個 long-running job 是否完成
通常會有 Push-basedPull-based 兩種模式。

sequenceDiagram participant Client as Client participant Server as Server Note over Client, Server: Pull-Based (Client keeps polling) rect rgba(255, 255, 255, 0.31) loop Repeatedly Client->>Server: Request state Server-->>Client: Respond with state end end Note over Client, Server: Push-Based (Server notifies Client) rect rgba(255, 255, 255, 0.31) Server->>Server: State changes Server-->>Client: Notify update end

上半部是 Pull-based,下半部是 Push-based

可以清楚看到

  • Pull-based 需要 Client 持續地向 Server 詢問目前狀態
  • Push-based 則是 當狀態改變時 Server 才主動通知 Client

CLI 工作流中的 Context Switching
#

在使用 CLI 時很常會需要跑一些執行時間較長的指令
如:執行一個需要花幾分鐘的 test、或是一個需要 build 的指令

這時候我們可能會先去做其他 task,但又需要時常回來看看這個指令的執行狀態
造成很多不必要的 context switching

使用 Push-based 通知來減少 Context Switching
#

如果有一個方式可以讓 CLI 執行完後主動通知我們
就可以如同 Push-based 的系統設計一樣,不需要重複去看這個指令的執行狀態

所以應該要有一個簡單的 script 可以在 CLI 執行完後主動通知我們

dotfiles/.zshrc at ee0772 · jason810496/dotfiles

144
145
146
147
148
149
150
151
152
153
154
155
# Utils
notify() {
  # Usage: <your long-running command>; notify
  # Useful for docker build, etc.
  if [[ $? -eq 0 ]]; then
    osascript -e 'display notification "✅ Success!" with title "Command Completed"'
    afplay /System/Library/Sounds/Glass.aiff
  else
    osascript -e 'display notification "❌ Failed!" with title "Command Failed"'
    afplay /System/Library/Sounds/Basso.aiff
  fi
}

目前我是把 notify 這個 script 加到我的 .zshrc
( 透過 macOS 的 osascript 來呼叫 display notification )

如何使用
#

以要 build 一個專案為例
這邊要用 ; 來串接指令而不是 &&|| 是因為要拿到 build 的結果
( 這樣才能知道 build 成功或失敗 )

make build ; notify "Build done"

在完成後會跳出以下的通知在右上角

成功的話

notify-success

失敗的話

notify-failed

總結
#

透過 Push-based 通知可以減少 CLI 工作流中的 context switching
讓我們可以更專注在其他 task 上
如果有類似的需求,可以參考上面的 script 來實作!

目前在貢獻 Apache Airflow 蠻常需要用到 Push-based 通知
例如:重新 build kubernetes 的 Docker image

breeze k8s build-k8s-image --rebuild-base-image ; notify

像這種需要跑很久的指令,可以更專心的做其他事情

例如寫這篇文章時其實就正在 build k8s image xD

相關文章

什麼是 Embedded Database? 簡介 RocksDB
·2 分鐘
Blog Zh-Tw Database
簡介 Embedded Database 和 RocksDB 的基本概念
2024 Dcard 暑期實習面試
·2 分鐘
Blog Zh-Tw Intern
2024 Dcard 暑期實習面試
2024 Appier 暑期實習面試
·2 分鐘
Blog Zh-Tw Intern
2024 Appier 暑期實習面試
成大資工大一上紀錄
·4 分鐘
Blog Zh-Tw
大一上到底做了什麼
Life Is Short Use 'uv'
·1 分鐘
Blog Zh-Tw Python
如何使用 uv 來管理你的 Python 專案
2024 Appier 暑期實習心得
·6 分鐘
Blog Zh-Tw Intern
在 Appier - Data Platform 部門的後端暑期實習心得