@sylix/coworker 2.0.11 → 2.0.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/dist/commands/slash/config.d.ts.map +1 -1
  2. package/dist/commands/slash/config.js +22 -4
  3. package/dist/commands/slash/config.js.map +1 -1
  4. package/dist/core/CoWorkerAgent.d.ts.map +1 -1
  5. package/dist/core/CoWorkerAgent.js +6 -3
  6. package/dist/core/CoWorkerAgent.js.map +1 -1
  7. package/dist/skills/defaults/accessibility/screen-reader-testing.md +545 -0
  8. package/dist/skills/defaults/accessibility/wcag-audit-patterns.md +555 -0
  9. package/dist/skills/defaults/ai-ml/rag.md +276 -0
  10. package/dist/skills/defaults/backend-development/api-design-principles.md +528 -0
  11. package/dist/skills/defaults/backend-development/api-design.md +285 -0
  12. package/dist/skills/defaults/backend-development/architecture-patterns.md +494 -0
  13. package/dist/skills/defaults/backend-development/async-python.md +237 -0
  14. package/dist/skills/defaults/backend-development/auth-implementation-patterns.md +638 -0
  15. package/dist/skills/defaults/backend-development/bazel-build-optimization.md +387 -0
  16. package/dist/skills/defaults/backend-development/billing-automation/SKILL.md +566 -0
  17. package/dist/skills/defaults/backend-development/code-review-excellence.md +538 -0
  18. package/dist/skills/defaults/backend-development/cqrs-implementation.md +554 -0
  19. package/dist/skills/defaults/backend-development/database-design.md +305 -0
  20. package/dist/skills/defaults/backend-development/debugging-strategies.md +536 -0
  21. package/dist/skills/defaults/backend-development/e2e-testing-patterns.md +544 -0
  22. package/dist/skills/defaults/backend-development/error-handling-patterns.md +641 -0
  23. package/dist/skills/defaults/backend-development/fastapi-templates.md +559 -0
  24. package/dist/skills/defaults/backend-development/fastapi.md +309 -0
  25. package/dist/skills/defaults/backend-development/git-advanced-workflows.md +405 -0
  26. package/dist/skills/defaults/backend-development/microservices-patterns.md +595 -0
  27. package/dist/skills/defaults/backend-development/microservices.md +284 -0
  28. package/dist/skills/defaults/backend-development/monorepo-management.md +623 -0
  29. package/dist/skills/defaults/backend-development/nodejs-backend-patterns.md +1048 -0
  30. package/dist/skills/defaults/backend-development/nx-workspace-patterns.md +457 -0
  31. package/dist/skills/defaults/backend-development/paypal-integration/SKILL.md +478 -0
  32. package/dist/skills/defaults/backend-development/pci-compliance/SKILL.md +480 -0
  33. package/dist/skills/defaults/backend-development/python-anti-patterns.md +349 -0
  34. package/dist/skills/defaults/backend-development/python-background-jobs.md +364 -0
  35. package/dist/skills/defaults/backend-development/python-code-style.md +360 -0
  36. package/dist/skills/defaults/backend-development/python-configuration.md +368 -0
  37. package/dist/skills/defaults/backend-development/python-design-patterns.md +296 -0
  38. package/dist/skills/defaults/backend-development/python-error-handling.md +323 -0
  39. package/dist/skills/defaults/backend-development/python-packaging.md +887 -0
  40. package/dist/skills/defaults/backend-development/python-performance-optimization.md +874 -0
  41. package/dist/skills/defaults/backend-development/python-project-structure.md +252 -0
  42. package/dist/skills/defaults/backend-development/python-resilience.md +376 -0
  43. package/dist/skills/defaults/backend-development/python-resource-management.md +421 -0
  44. package/dist/skills/defaults/backend-development/python-type-safety.md +428 -0
  45. package/dist/skills/defaults/backend-development/sql-optimization-patterns.md +509 -0
  46. package/dist/skills/defaults/backend-development/stripe-integration/SKILL.md +522 -0
  47. package/dist/skills/defaults/backend-development/turborepo-caching.md +376 -0
  48. package/dist/skills/defaults/blockchain/defi-protocol-templates.md +430 -0
  49. package/dist/skills/defaults/blockchain/nft-standards.md +364 -0
  50. package/dist/skills/defaults/blockchain/solidity-security.md +514 -0
  51. package/dist/skills/defaults/blockchain/web3-testing.md +360 -0
  52. package/dist/skills/defaults/business/competitive-landscape/SKILL.md +527 -0
  53. package/dist/skills/defaults/business/market-sizing-analysis/SKILL.md +451 -0
  54. package/dist/skills/defaults/business/startup-financial-modeling/SKILL.md +494 -0
  55. package/dist/skills/defaults/business/startup-metrics-framework/SKILL.md +564 -0
  56. package/dist/skills/defaults/business/team-composition-analysis.md +437 -0
  57. package/dist/skills/defaults/compliance/employment-contract-templates/SKILL.md +527 -0
  58. package/dist/skills/defaults/compliance/gdpr-data-handling/SKILL.md +630 -0
  59. package/dist/skills/defaults/data-engineering/airflow-dag-patterns.md +436 -0
  60. package/dist/skills/defaults/data-engineering/airflow.md +519 -0
  61. package/dist/skills/defaults/data-engineering/data-quality.md +583 -0
  62. package/dist/skills/defaults/data-engineering/dbt-transformation-patterns.md +482 -0
  63. package/dist/skills/defaults/data-engineering/dbt.md +556 -0
  64. package/dist/skills/defaults/data-engineering/ml-pipeline-workflow/SKILL.md +247 -0
  65. package/dist/skills/defaults/data-engineering/spark-optimization.md +348 -0
  66. package/dist/skills/defaults/data-engineering/spark.md +411 -0
  67. package/dist/skills/defaults/database/postgresql.md +202 -0
  68. package/dist/skills/defaults/debugging/systematic-debugging.md +249 -0
  69. package/dist/skills/defaults/devops/architecture-decision-records.md +448 -0
  70. package/dist/skills/defaults/devops/changelog-automation.md +580 -0
  71. package/dist/skills/defaults/devops/cicd.md +314 -0
  72. package/dist/skills/defaults/devops/cloud.md +263 -0
  73. package/dist/skills/defaults/devops/code-review-excellence.md +299 -0
  74. package/dist/skills/defaults/devops/cost-optimization.md +295 -0
  75. package/dist/skills/defaults/devops/deployment-pipeline-design.md +356 -0
  76. package/dist/skills/defaults/devops/docker.md +281 -0
  77. package/dist/skills/defaults/devops/git-workflows.md +205 -0
  78. package/dist/skills/defaults/devops/github-actions.md +311 -0
  79. package/dist/skills/defaults/devops/gitlab-ci-patterns.md +266 -0
  80. package/dist/skills/defaults/devops/hybrid-cloud-networking.md +241 -0
  81. package/dist/skills/defaults/devops/istio-traffic-management.md +327 -0
  82. package/dist/skills/defaults/devops/kubernetes.md +339 -0
  83. package/dist/skills/defaults/devops/linkerd-patterns.md +311 -0
  84. package/dist/skills/defaults/devops/multi-cloud-architecture.md +181 -0
  85. package/dist/skills/defaults/devops/observability.md +243 -0
  86. package/dist/skills/defaults/devops/openapi-spec-generation.md +1024 -0
  87. package/dist/skills/defaults/devops/postmortem-writing.md +396 -0
  88. package/dist/skills/defaults/devops/prometheus-configuration.md +265 -0
  89. package/dist/skills/defaults/devops/secrets-management.md +341 -0
  90. package/dist/skills/defaults/devops/service-mesh-observability.md +385 -0
  91. package/dist/skills/defaults/devops/terraform-module-library.md +244 -0
  92. package/dist/skills/defaults/finance/backtesting-frameworks/SKILL.md +663 -0
  93. package/dist/skills/defaults/finance/risk-metrics-calculation/SKILL.md +557 -0
  94. package/dist/skills/defaults/frontend/accessibility-compliance.md +420 -0
  95. package/dist/skills/defaults/frontend/design-system-patterns.md +337 -0
  96. package/dist/skills/defaults/frontend/interaction-design.md +327 -0
  97. package/dist/skills/defaults/frontend/javascript.md +311 -0
  98. package/dist/skills/defaults/frontend/modern-javascript-patterns.md +927 -0
  99. package/dist/skills/defaults/frontend/react-native-design.md +440 -0
  100. package/dist/skills/defaults/frontend/react.md +345 -0
  101. package/dist/skills/defaults/frontend/responsive-design.md +472 -0
  102. package/dist/skills/defaults/frontend/tailwind-design-system.md +337 -0
  103. package/dist/skills/defaults/frontend/typescript-advanced-types.md +724 -0
  104. package/dist/skills/defaults/frontend/typescript.md +334 -0
  105. package/dist/skills/defaults/frontend/visual-design-foundations.md +326 -0
  106. package/dist/skills/defaults/frontend/web-component-design.md +279 -0
  107. package/dist/skills/defaults/game-development/godot-gdscript-patterns.md +188 -0
  108. package/dist/skills/defaults/game-development/unity-ecs-patterns.md +594 -0
  109. package/dist/skills/defaults/kubernetes/gitops-workflow.md +285 -0
  110. package/dist/skills/defaults/kubernetes/gitops.md +280 -0
  111. package/dist/skills/defaults/kubernetes/helm-chart-scaffolding.md +553 -0
  112. package/dist/skills/defaults/kubernetes/helm.md +343 -0
  113. package/dist/skills/defaults/kubernetes/k8s-manifest-generator.md +501 -0
  114. package/dist/skills/defaults/kubernetes/k8s-security-policies.md +342 -0
  115. package/dist/skills/defaults/kubernetes/manifests.md +330 -0
  116. package/dist/skills/defaults/kubernetes/security.md +337 -0
  117. package/dist/skills/defaults/llm-application/embedding-strategies.md +608 -0
  118. package/dist/skills/defaults/llm-application/hybrid-search-implementation.md +570 -0
  119. package/dist/skills/defaults/llm-application/hybrid-search.md +570 -0
  120. package/dist/skills/defaults/llm-application/langchain-architecture.md +666 -0
  121. package/dist/skills/defaults/llm-application/langchain.md +259 -0
  122. package/dist/skills/defaults/llm-application/llm-evaluation.md +695 -0
  123. package/dist/skills/defaults/llm-application/prompt-engineering-patterns.md +449 -0
  124. package/dist/skills/defaults/llm-application/prompt-engineering.md +219 -0
  125. package/dist/skills/defaults/llm-application/rag-implementation.md +434 -0
  126. package/dist/skills/defaults/llm-application/similarity-search-patterns.md +560 -0
  127. package/dist/skills/defaults/llm-application/similarity-search.md +560 -0
  128. package/dist/skills/defaults/llm-application/vector-index-tuning.md +523 -0
  129. package/dist/skills/defaults/mobile/mobile-android-design.md +440 -0
  130. package/dist/skills/defaults/mobile/mobile-ios-design.md +266 -0
  131. package/dist/skills/defaults/monitoring/distributed-tracing.md +436 -0
  132. package/dist/skills/defaults/monitoring/grafana-dashboards.md +370 -0
  133. package/dist/skills/defaults/monitoring/prometheus-configuration.md +379 -0
  134. package/dist/skills/defaults/monitoring/slo-implementation.md +323 -0
  135. package/dist/skills/defaults/refactoring/code-refactoring.md +349 -0
  136. package/dist/skills/defaults/security/anti-reversing-techniques/SKILL.md +559 -0
  137. package/dist/skills/defaults/security/auditor.md +168 -0
  138. package/dist/skills/defaults/security/binary-analysis-patterns/SKILL.md +438 -0
  139. package/dist/skills/defaults/security/memory-forensics/SKILL.md +483 -0
  140. package/dist/skills/defaults/security/mtls-configuration.md +349 -0
  141. package/dist/skills/defaults/security/protocol-reverse-engineering/SKILL.md +520 -0
  142. package/dist/skills/defaults/security/sast-configuration.md +182 -0
  143. package/dist/skills/defaults/security/security.md +313 -0
  144. package/dist/skills/defaults/security/stride-analysis.md +273 -0
  145. package/dist/skills/defaults/security/threat-mitigation-mapping.md +290 -0
  146. package/dist/skills/defaults/systems/bash-defensive-patterns/SKILL.md +539 -0
  147. package/dist/skills/defaults/systems/bats-testing-patterns/SKILL.md +631 -0
  148. package/dist/skills/defaults/systems/go-concurrency-patterns.md +657 -0
  149. package/dist/skills/defaults/systems/memory-safety-patterns.md +605 -0
  150. package/dist/skills/defaults/systems/rust-async-patterns.md +519 -0
  151. package/dist/skills/defaults/systems/shellcheck-configuration/SKILL.md +456 -0
  152. package/dist/skills/defaults/team-collaboration/multi-reviewer-patterns.md +126 -0
  153. package/dist/skills/defaults/team-collaboration/parallel-feature-development.md +151 -0
  154. package/dist/skills/defaults/testing/javascript-testing-patterns.md +1021 -0
  155. package/dist/skills/defaults/testing/python-testing-patterns.md +351 -0
  156. package/dist/skills/defaults/testing/testing.md +332 -0
  157. package/dist/skills/defaults/workflows/context-driven-development.md +384 -0
  158. package/dist/skills/defaults/workflows/track-management.md +592 -0
  159. package/dist/skills/defaults/workflows/workflow-patterns.md +622 -0
  160. package/dist/skills/index.d.ts +11 -0
  161. package/dist/skills/index.d.ts.map +1 -0
  162. package/dist/skills/index.js +129 -0
  163. package/dist/skills/index.js.map +1 -0
  164. package/dist/utils/character.js +4 -4
  165. package/dist/utils/character.js.map +1 -1
  166. package/dist/utils/inputbar.d.ts.map +1 -1
  167. package/dist/utils/inputbar.js +7 -0
  168. package/dist/utils/inputbar.js.map +1 -1
  169. package/package.json +1 -1
@@ -0,0 +1,519 @@
1
+ ---
2
+ name: rust-async-patterns
3
+ description: Master Rust async programming with Tokio, async traits, error handling, and concurrent patterns. Use when building async Rust applications, implementing concurrent systems, or debugging async code.
4
+ ---
5
+
6
+ # Rust Async Patterns
7
+
8
+ Production patterns for async Rust programming with Tokio runtime, including tasks, channels, streams, and error handling.
9
+
10
+ ## When to Use This Skill
11
+
12
+ - Building async Rust applications
13
+ - Implementing concurrent network services
14
+ - Using Tokio for async I/O
15
+ - Handling async errors properly
16
+ - Debugging async code issues
17
+ - Optimizing async performance
18
+
19
+ ## Core Concepts
20
+
21
+ ### 1. Async Execution Model
22
+
23
+ ```
24
+ Future (lazy) → poll() → Ready(value) | Pending
25
+ ↑ ↓
26
+ Waker ← Runtime schedules
27
+ ```
28
+
29
+ ### 2. Key Abstractions
30
+
31
+ | Concept | Purpose |
32
+ | ---------- | ---------------------------------------- |
33
+ | `Future` | Lazy computation that may complete later |
34
+ | `async fn` | Function returning impl Future |
35
+ | `await` | Suspend until future completes |
36
+ | `Task` | Spawned future running concurrently |
37
+ | `Runtime` | Executor that polls futures |
38
+
39
+ ## Quick Start
40
+
41
+ ```toml
42
+ # Cargo.toml
43
+ [dependencies]
44
+ tokio = { version = "1", features = ["full"] }
45
+ futures = "0.3"
46
+ async-trait = "0.1"
47
+ anyhow = "1.0"
48
+ tracing = "0.1"
49
+ tracing-subscriber = "0.3"
50
+ ```
51
+
52
+ ```rust
53
+ use tokio::time::{sleep, Duration};
54
+ use anyhow::Result;
55
+
56
+ #[tokio::main]
57
+ async fn main() -> Result<()> {
58
+ // Initialize tracing
59
+ tracing_subscriber::fmt::init();
60
+
61
+ // Async operations
62
+ let result = fetch_data("https://api.example.com").await?;
63
+ println!("Got: {}", result);
64
+
65
+ Ok(())
66
+ }
67
+
68
+ async fn fetch_data(url: &str) -> Result<String> {
69
+ // Simulated async operation
70
+ sleep(Duration::from_millis(100)).await;
71
+ Ok(format!("Data from {}", url))
72
+ }
73
+ ```
74
+
75
+ ## Patterns
76
+
77
+ ### Pattern 1: Concurrent Task Execution
78
+
79
+ ```rust
80
+ use tokio::task::JoinSet;
81
+ use anyhow::Result;
82
+
83
+ // Spawn multiple concurrent tasks
84
+ async fn fetch_all_concurrent(urls: Vec<String>) -> Result<Vec<String>> {
85
+ let mut set = JoinSet::new();
86
+
87
+ for url in urls {
88
+ set.spawn(async move {
89
+ fetch_data(&url).await
90
+ });
91
+ }
92
+
93
+ let mut results = Vec::new();
94
+ while let Some(res) = set.join_next().await {
95
+ match res {
96
+ Ok(Ok(data)) => results.push(data),
97
+ Ok(Err(e)) => tracing::error!("Task failed: {}", e),
98
+ Err(e) => tracing::error!("Join error: {}", e),
99
+ }
100
+ }
101
+
102
+ Ok(results)
103
+ }
104
+
105
+ // With concurrency limit
106
+ use futures::stream::{self, StreamExt};
107
+
108
+ async fn fetch_with_limit(urls: Vec<String>, limit: usize) -> Vec<Result<String>> {
109
+ stream::iter(urls)
110
+ .map(|url| async move { fetch_data(&url).await })
111
+ .buffer_unordered(limit) // Max concurrent tasks
112
+ .collect()
113
+ .await
114
+ }
115
+
116
+ // Select first to complete
117
+ use tokio::select;
118
+
119
+ async fn race_requests(url1: &str, url2: &str) -> Result<String> {
120
+ select! {
121
+ result = fetch_data(url1) => result,
122
+ result = fetch_data(url2) => result,
123
+ }
124
+ }
125
+ ```
126
+
127
+ ### Pattern 2: Channels for Communication
128
+
129
+ ```rust
130
+ use tokio::sync::{mpsc, broadcast, oneshot, watch};
131
+
132
+ // Multi-producer, single-consumer
133
+ async fn mpsc_example() {
134
+ let (tx, mut rx) = mpsc::channel::<String>(100);
135
+
136
+ // Spawn producer
137
+ let tx2 = tx.clone();
138
+ tokio::spawn(async move {
139
+ tx2.send("Hello".to_string()).await.unwrap();
140
+ });
141
+
142
+ // Consume
143
+ while let Some(msg) = rx.recv().await {
144
+ println!("Got: {}", msg);
145
+ }
146
+ }
147
+
148
+ // Broadcast: multi-producer, multi-consumer
149
+ async fn broadcast_example() {
150
+ let (tx, _) = broadcast::channel::<String>(100);
151
+
152
+ let mut rx1 = tx.subscribe();
153
+ let mut rx2 = tx.subscribe();
154
+
155
+ tx.send("Event".to_string()).unwrap();
156
+
157
+ // Both receivers get the message
158
+ let _ = rx1.recv().await;
159
+ let _ = rx2.recv().await;
160
+ }
161
+
162
+ // Oneshot: single value, single use
163
+ async fn oneshot_example() -> String {
164
+ let (tx, rx) = oneshot::channel::<String>();
165
+
166
+ tokio::spawn(async move {
167
+ tx.send("Result".to_string()).unwrap();
168
+ });
169
+
170
+ rx.await.unwrap()
171
+ }
172
+
173
+ // Watch: single producer, multi-consumer, latest value
174
+ async fn watch_example() {
175
+ let (tx, mut rx) = watch::channel("initial".to_string());
176
+
177
+ tokio::spawn(async move {
178
+ loop {
179
+ // Wait for changes
180
+ rx.changed().await.unwrap();
181
+ println!("New value: {}", *rx.borrow());
182
+ }
183
+ });
184
+
185
+ tx.send("updated".to_string()).unwrap();
186
+ }
187
+ ```
188
+
189
+ ### Pattern 3: Async Error Handling
190
+
191
+ ```rust
192
+ use anyhow::{Context, Result, bail};
193
+ use thiserror::Error;
194
+
195
+ #[derive(Error, Debug)]
196
+ pub enum ServiceError {
197
+ #[error("Network error: {0}")]
198
+ Network(#[from] reqwest::Error),
199
+
200
+ #[error("Database error: {0}")]
201
+ Database(#[from] sqlx::Error),
202
+
203
+ #[error("Not found: {0}")]
204
+ NotFound(String),
205
+
206
+ #[error("Timeout after {0:?}")]
207
+ Timeout(std::time::Duration),
208
+ }
209
+
210
+ // Using anyhow for application errors
211
+ async fn process_request(id: &str) -> Result<Response> {
212
+ let data = fetch_data(id)
213
+ .await
214
+ .context("Failed to fetch data")?;
215
+
216
+ let parsed = parse_response(&data)
217
+ .context("Failed to parse response")?;
218
+
219
+ Ok(parsed)
220
+ }
221
+
222
+ // Using custom errors for library code
223
+ async fn get_user(id: &str) -> Result<User, ServiceError> {
224
+ let result = db.query(id).await?;
225
+
226
+ match result {
227
+ Some(user) => Ok(user),
228
+ None => Err(ServiceError::NotFound(id.to_string())),
229
+ }
230
+ }
231
+
232
+ // Timeout wrapper
233
+ use tokio::time::timeout;
234
+
235
+ async fn with_timeout<T, F>(duration: Duration, future: F) -> Result<T, ServiceError>
236
+ where
237
+ F: std::future::Future<Output = Result<T, ServiceError>>,
238
+ {
239
+ timeout(duration, future)
240
+ .await
241
+ .map_err(|_| ServiceError::Timeout(duration))?
242
+ }
243
+ ```
244
+
245
+ ### Pattern 4: Graceful Shutdown
246
+
247
+ ```rust
248
+ use tokio::signal;
249
+ use tokio::sync::broadcast;
250
+ use tokio_util::sync::CancellationToken;
251
+
252
+ async fn run_server() -> Result<()> {
253
+ // Method 1: CancellationToken
254
+ let token = CancellationToken::new();
255
+ let token_clone = token.clone();
256
+
257
+ // Spawn task that respects cancellation
258
+ tokio::spawn(async move {
259
+ loop {
260
+ tokio::select! {
261
+ _ = token_clone.cancelled() => {
262
+ tracing::info!("Task shutting down");
263
+ break;
264
+ }
265
+ _ = do_work() => {}
266
+ }
267
+ }
268
+ });
269
+
270
+ // Wait for shutdown signal
271
+ signal::ctrl_c().await?;
272
+ tracing::info!("Shutdown signal received");
273
+
274
+ // Cancel all tasks
275
+ token.cancel();
276
+
277
+ // Give tasks time to cleanup
278
+ tokio::time::sleep(Duration::from_secs(5)).await;
279
+
280
+ Ok(())
281
+ }
282
+
283
+ // Method 2: Broadcast channel for shutdown
284
+ async fn run_with_broadcast() -> Result<()> {
285
+ let (shutdown_tx, _) = broadcast::channel::<()>(1);
286
+
287
+ let mut rx = shutdown_tx.subscribe();
288
+ tokio::spawn(async move {
289
+ tokio::select! {
290
+ _ = rx.recv() => {
291
+ tracing::info!("Received shutdown");
292
+ }
293
+ _ = async { loop { do_work().await } } => {}
294
+ }
295
+ });
296
+
297
+ signal::ctrl_c().await?;
298
+ let _ = shutdown_tx.send(());
299
+
300
+ Ok(())
301
+ }
302
+ ```
303
+
304
+ ### Pattern 5: Async Traits
305
+
306
+ ```rust
307
+ use async_trait::async_trait;
308
+
309
+ #[async_trait]
310
+ pub trait Repository {
311
+ async fn get(&self, id: &str) -> Result<Entity>;
312
+ async fn save(&self, entity: &Entity) -> Result<()>;
313
+ async fn delete(&self, id: &str) -> Result<()>;
314
+ }
315
+
316
+ pub struct PostgresRepository {
317
+ pool: sqlx::PgPool,
318
+ }
319
+
320
+ #[async_trait]
321
+ impl Repository for PostgresRepository {
322
+ async fn get(&self, id: &str) -> Result<Entity> {
323
+ sqlx::query_as!(Entity, "SELECT * FROM entities WHERE id = $1", id)
324
+ .fetch_one(&self.pool)
325
+ .await
326
+ .map_err(Into::into)
327
+ }
328
+
329
+ async fn save(&self, entity: &Entity) -> Result<()> {
330
+ sqlx::query!(
331
+ "INSERT INTO entities (id, data) VALUES ($1, $2)
332
+ ON CONFLICT (id) DO UPDATE SET data = $2",
333
+ entity.id,
334
+ entity.data
335
+ )
336
+ .execute(&self.pool)
337
+ .await?;
338
+ Ok(())
339
+ }
340
+
341
+ async fn delete(&self, id: &str) -> Result<()> {
342
+ sqlx::query!("DELETE FROM entities WHERE id = $1", id)
343
+ .execute(&self.pool)
344
+ .await?;
345
+ Ok(())
346
+ }
347
+ }
348
+
349
+ // Trait object usage
350
+ async fn process(repo: &dyn Repository, id: &str) -> Result<()> {
351
+ let entity = repo.get(id).await?;
352
+ // Process...
353
+ repo.save(&entity).await
354
+ }
355
+ ```
356
+
357
+ ### Pattern 6: Streams and Async Iteration
358
+
359
+ ```rust
360
+ use futures::stream::{self, Stream, StreamExt};
361
+ use async_stream::stream;
362
+
363
+ // Create stream from async iterator
364
+ fn numbers_stream() -> impl Stream<Item = i32> {
365
+ stream! {
366
+ for i in 0..10 {
367
+ tokio::time::sleep(Duration::from_millis(100)).await;
368
+ yield i;
369
+ }
370
+ }
371
+ }
372
+
373
+ // Process stream
374
+ async fn process_stream() {
375
+ let stream = numbers_stream();
376
+
377
+ // Map and filter
378
+ let processed: Vec<_> = stream
379
+ .filter(|n| futures::future::ready(*n % 2 == 0))
380
+ .map(|n| n * 2)
381
+ .collect()
382
+ .await;
383
+
384
+ println!("{:?}", processed);
385
+ }
386
+
387
+ // Chunked processing
388
+ async fn process_in_chunks() {
389
+ let stream = numbers_stream();
390
+
391
+ let mut chunks = stream.chunks(3);
392
+
393
+ while let Some(chunk) = chunks.next().await {
394
+ println!("Processing chunk: {:?}", chunk);
395
+ }
396
+ }
397
+
398
+ // Merge multiple streams
399
+ async fn merge_streams() {
400
+ let stream1 = numbers_stream();
401
+ let stream2 = numbers_stream();
402
+
403
+ let merged = stream::select(stream1, stream2);
404
+
405
+ merged
406
+ .for_each(|n| async move {
407
+ println!("Got: {}", n);
408
+ })
409
+ .await;
410
+ }
411
+ ```
412
+
413
+ ### Pattern 7: Resource Management
414
+
415
+ ```rust
416
+ use std::sync::Arc;
417
+ use tokio::sync::{Mutex, RwLock, Semaphore};
418
+
419
+ // Shared state with RwLock (prefer for read-heavy)
420
+ struct Cache {
421
+ data: RwLock<HashMap<String, String>>,
422
+ }
423
+
424
+ impl Cache {
425
+ async fn get(&self, key: &str) -> Option<String> {
426
+ self.data.read().await.get(key).cloned()
427
+ }
428
+
429
+ async fn set(&self, key: String, value: String) {
430
+ self.data.write().await.insert(key, value);
431
+ }
432
+ }
433
+
434
+ // Connection pool with semaphore
435
+ struct Pool {
436
+ semaphore: Semaphore,
437
+ connections: Mutex<Vec<Connection>>,
438
+ }
439
+
440
+ impl Pool {
441
+ fn new(size: usize) -> Self {
442
+ Self {
443
+ semaphore: Semaphore::new(size),
444
+ connections: Mutex::new((0..size).map(|_| Connection::new()).collect()),
445
+ }
446
+ }
447
+
448
+ async fn acquire(&self) -> PooledConnection<'_> {
449
+ let permit = self.semaphore.acquire().await.unwrap();
450
+ let conn = self.connections.lock().await.pop().unwrap();
451
+ PooledConnection { pool: self, conn: Some(conn), _permit: permit }
452
+ }
453
+ }
454
+
455
+ struct PooledConnection<'a> {
456
+ pool: &'a Pool,
457
+ conn: Option<Connection>,
458
+ _permit: tokio::sync::SemaphorePermit<'a>,
459
+ }
460
+
461
+ impl Drop for PooledConnection<'_> {
462
+ fn drop(&mut self) {
463
+ if let Some(conn) = self.conn.take() {
464
+ let pool = self.pool;
465
+ tokio::spawn(async move {
466
+ pool.connections.lock().await.push(conn);
467
+ });
468
+ }
469
+ }
470
+ }
471
+ ```
472
+
473
+ ## Debugging Tips
474
+
475
+ ```rust
476
+ // Enable tokio-console for runtime debugging
477
+ // Cargo.toml: tokio = { features = ["tracing"] }
478
+ // Run: RUSTFLAGS="--cfg tokio_unstable" cargo run
479
+ // Then: tokio-console
480
+
481
+ // Instrument async functions
482
+ use tracing::instrument;
483
+
484
+ #[instrument(skip(pool))]
485
+ async fn fetch_user(pool: &PgPool, id: &str) -> Result<User> {
486
+ tracing::debug!("Fetching user");
487
+ // ...
488
+ }
489
+
490
+ // Track task spawning
491
+ let span = tracing::info_span!("worker", id = %worker_id);
492
+ tokio::spawn(async move {
493
+ // Enters span when polled
494
+ }.instrument(span));
495
+ ```
496
+
497
+ ## Best Practices
498
+
499
+ ### Do's
500
+
501
+ - **Use `tokio::select!`** - For racing futures
502
+ - **Prefer channels** - Over shared state when possible
503
+ - **Use `JoinSet`** - For managing multiple tasks
504
+ - **Instrument with tracing** - For debugging async code
505
+ - **Handle cancellation** - Check `CancellationToken`
506
+
507
+ ### Don'ts
508
+
509
+ - **Don't block** - Never use `std::thread::sleep` in async
510
+ - **Don't hold locks across awaits** - Causes deadlocks
511
+ - **Don't spawn unboundedly** - Use semaphores for limits
512
+ - **Don't ignore errors** - Propagate with `?` or log
513
+ - **Don't forget Send bounds** - For spawned futures
514
+
515
+ ## Resources
516
+
517
+ - [Tokio Tutorial](https://tokio.rs/tokio/tutorial)
518
+ - [Async Book](https://rust-lang.github.io/async-book/)
519
+ - [Tokio Console](https://github.com/tokio-rs/console)