Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.
Python aianthropicautomationclaude-codeclaude-skillscloudflaredevtoolsproductivityreactskillstailwindvite
feat(snowflake-platform): Add REST API patterns for Cloudflare Workers
Jez8684f3f931e1
diff --git a/skills/snowflake-platform/README.md b/skills/snowflake-platform/README.mdindex 5f526f01..31e118f2 100644--- a/skills/snowflake-platform/README.md+++ b/skills/snowflake-platform/README.md@@ -53,6 +53,15 @@ This skill activates when conversations include:- snowflake udf- snowflake stored procedure+**REST API:**+- snowflake rest api+- snowflake sql api+- /api/v2/statements+- statementHandle+- statementStatusUrl+- snowflake polling+- snowflake async query+**Errors:**- jwt validation error snowflake- account identifier@@ -60,15 +69,20 @@ This skill activates when conversations include:- external access integration- release directive- security review status+- Unsupported Accept header null+- Too many subrequests+- 090001 snowflake+- statementHandle timeout## What This Skill Covers1. **Snow CLI** - Project management, SQL execution, app deployment-2. **Cortex AI** - LLM functions in SQL (COMPLETE, SUMMARIZE, TRANSLATE, etc.)-3. **Native Apps** - Development, versioning, marketplace publishing-4. **Authentication** - JWT key-pair, account identifiers (critical gotcha)-5. **Snowpark** - Python DataFrame API, UDFs, stored procedures-6. **Marketplace** - Security review, Provider Studio, paid listings+2. **REST API** - SQL API v2, async queries, polling, Cloudflare Workers integration+3. **Cortex AI** - LLM functions in SQL (COMPLETE, SUMMARIZE, TRANSLATE, etc.)+4. **Native Apps** - Development, versioning, marketplace publishing+5. **Authentication** - JWT key-pair, account identifiers (critical gotcha)+6. **Snowpark** - Python DataFrame API, UDFs, stored procedures+7. **Marketplace** - Security review, Provider Studio, paid listings## What This Skill Does NOT Cover@@ -80,6 +94,9 @@ This skill activates when conversations include:## Key Corrections- Account identifier confusion (org-account vs locator)+- REST API missing Accept header on polling+- Workers fetch timeout (use AbortSignal)+- Subrequest limits during polling- External access integration reset after deploys- Release channel syntax (CLI vs legacy SQL)- Artifact nesting in snowflake.ymldiff --git a/skills/snowflake-platform/SKILL.md b/skills/snowflake-platform/SKILL.mdindex ed3e073b..72d26a95 100644--- a/skills/snowflake-platform/SKILL.md+++ b/skills/snowflake-platform/SKILL.md@@ -543,6 +543,77 @@ def my_sproc(session: Session, table_name: str) -> str:return f"Row count: {count}"```+## REST API (SQL API v2)++The REST API is the foundation for programmatic Snowflake access from Cloudflare Workers.++### Endpoint++```+https://{org-account}.snowflakecomputing.com/api/v2/statements+```++### Required Headers (CRITICAL)++**ALL requests** must include these headers - missing `Accept` causes silent failures:++```typescript+const headers = {+ 'Authorization': `Bearer ${jwt}`,+ 'Content-Type': 'application/json',+ 'Accept': 'application/json', // REQUIRED - "null" error if missing+ 'User-Agent': 'MyApp/1.0',+};+```++### Async Query Handling++Even simple queries return async (HTTP 202). Always implement polling:++```typescript+// Submit returns statementHandle, not results+const submit = await fetch(url, { method: 'POST', headers, body });+const { statementHandle } = await submit.json();++// Poll until complete+while (true) {+ const status = await fetch(`${url}/${statementHandle}`, { headers });+ if (status.status === 200) break; // Complete+ if (status.status === 202) {+ await sleep(2000); // Still running+ continue;+ }+}+```++### Workers Subrequest Limits++| Plan | Limit | Safe Polling |+|------|-------|--------------|+| Free | 50 | 45 attempts @ 2s = 90s max |+| Paid | 1,000 | 100 attempts @ 500ms = 50s max |++### Fetch Timeouts++Workers `fetch()` has **no default timeout**. Always use AbortController:++```typescript+const response = await fetch(url, {+ signal: AbortSignal.timeout(30000), // 30 seconds+ headers,+});+```++### Cancel on Timeout++Cancel queries when timeout occurs to avoid warehouse costs:++```+POST /api/v2/statements/{statementHandle}/cancel+```++See `templates/snowflake-rest-client.ts` for complete implementation.+## Known Issues### 1. Account Identifier Confusion@@ -585,9 +656,43 @@ def my_sproc(session: Session, table_name: str) -> str:**Fix**: Always grant REFERENCE_USAGE before `snow app run` when using external databases.+### 6. REST API Missing Accept Header++**Symptom**: "Unsupported Accept header null is specified" on polling requests.++**Cause**: Initial request had `Accept: application/json` but polling request didn't.++**Fix**: Use consistent headers helper function for ALL requests (submit, poll, cancel).++### 7. Workers Fetch Hangs Forever++**Symptom**: Worker hangs indefinitely waiting for Snowflake response.++**Cause**: Cloudflare Workers' `fetch()` has no default timeout.++**Fix**: Always use `AbortSignal.timeout(30000)` on all Snowflake requests.++### 8. Too Many Subrequests++**Symptom**: "Too many subrequests" error during polling.++**Cause**: Polling every 1 second × 600 attempts = 600 subrequests exceeds limits.++**Fix**: Poll every 2-5 seconds, limit to 45 (free) or 100 (paid) attempts.++### 9. Warehouse Not Auto-Resuming (Perceived)++**Symptom**: Queries return statementHandle but never complete (code 090001 indefinitely).++**Cause**: `090001` means "running" not error. Warehouse IS resuming, just takes time.++**Fix**: Auto-resume works. Wait longer or explicitly resume first: `POST /api/v2/warehouses/{wh}:resume`+## References- [Snowflake CLI Documentation](https://docs.snowflake.com/en/developer-guide/snowflake-cli/index)+- [SQL REST API Reference](https://docs.snowflake.com/en/developer-guide/sql-api/reference)+- [SQL API Authentication](https://docs.snowflake.com/en/developer-guide/sql-api/authenticating)- [Cortex AI Functions](https://docs.snowflake.com/en/user-guide/snowflake-cortex/llm-functions)- [Native Apps Framework](https://docs.snowflake.com/en/developer-guide/native-apps/native-apps-about)- [Snowpark Python](https://docs.snowflake.com/en/developer-guide/snowpark/python/index)diff --git a/skills/snowflake-platform/references/rest-api-guide.md b/skills/snowflake-platform/references/rest-api-guide.mdnew file mode 100644index 00000000..e055d7cb--- /dev/null+++ b/skills/snowflake-platform/references/rest-api-guide.md@@ -0,0 +1,172 @@+# Snowflake REST API (SQL API v2) Reference++Comprehensive guide for Snowflake REST API integration, especially for Cloudflare Workers.++## Endpoint++```+https://{account-identifier}.snowflakecomputing.com/api/v2/statements+```++Use **organization-account** format: `myorg-myaccount` (not account locator).++## Required Headers (ALL Endpoints)++Every Snowflake REST API request requires these headers:++| Header | Value | Notes |+|--------|-------|-------|+| `Authorization` | `Bearer <jwt_token>` | Required |+| `Accept` | `application/json` | **Required - causes "null" error if missing** |+| `Content-Type` | `application/json` | Required for POST |+| `User-Agent` | `MyApp/1.0` | Required (RFC 7231) |++**Optional but recommended:**++| Header | Value |+|--------|-------|+| `X-Snowflake-Authorization-Token-Type` | `KEYPAIR_JWT` |+| `X-Snowflake-Role` | `MY_ROLE` |+| `X-Snowflake-Warehouse` | `MY_WH` |++## Async Query Behavior++**Critical**: Even simple queries like `SELECT CURRENT_TIMESTAMP()` may return async (HTTP 202).++| Response Code | Meaning | Action |+|---------------|---------|--------|+| **200** | Query complete | Parse `data` array from response |+| **202** | Still executing | Poll `statementStatusUrl` |+| **408** | Timeout | Query exceeded timeout |+| **422** | Execution error | Check `message` for details |+| **429** | Rate limited | Retry with backoff |++### Response Format (202 Accepted)++```json+{+ "code": "090001",+ "sqlState": "00000",+ "message": "Statement executed successfully.",+ "statementHandle": "01abc123-0000-0000-0000-000000000000",+ "statementStatusUrl": "/api/v2/statements/01abc123-..."+}+```++### Status Code 090001++`090001` with `sqlState: "00000"` means **success** (query still running or complete), not an error.++## Polling Best Practices++### Cloudflare Workers Constraints++| Plan | Subrequest Limit | Max Poll Attempts |+|------|------------------|-------------------|+| **Free** | 50 | ~45 (leave buffer) |+| **Paid** | 1,000 | ~100 (conservative) |++### Recommended Configuration++```typescript+// Free plan+const POLLING_CONFIG = {+ intervalMs: 2000, // Poll every 2 seconds+ maxAttempts: 45, // Stay under 50 limit+ fetchTimeoutMs: 30000, // 30s per request+ totalTimeoutMs: 90000, // 90s total+};++// Paid plan+const POLLING_CONFIG = {+ intervalMs: 500, // Poll every 500ms+ maxAttempts: 100, // Stay well under 1000+ fetchTimeoutMs: 30000,+ totalTimeoutMs: 60000,+};+```++## Warehouse Auto-Resume++Auto-resume **works** with REST API when `AUTO_RESUME = TRUE` (default).++| Warehouse Size | Resume Time |+|----------------|-------------|+| X-Small/Small | 1-2 seconds |+| Medium | 1-3 seconds |+| Large+ | 2-5+ seconds |++**For time-sensitive operations**, explicitly resume first:++```+POST /api/v2/warehouses/{warehouse_name}:resume+```++Or via SQL API:+```sql+ALTER WAREHOUSE MY_WH RESUME IF SUSPENDED+```++## JWT Authentication Format++### Claims++| Claim | Format |+|-------|--------|+| `iss` | `ACCOUNT.USERNAME.SHA256:fingerprint` |+| `sub` | `ACCOUNT.USERNAME` |+| `iat` | Unix timestamp (seconds) |+| `exp` | Max 1 hour from iat |++**Account identifier**: Use `MYORG-MYACCOUNT` format (uppercase).++### Finding Your Identifiers++```sql+SELECT CURRENT_ORGANIZATION_NAME() || '-' || CURRENT_ACCOUNT_NAME();+-- Returns: MYORG-MYACCOUNT++SELECT CURRENT_ACCOUNT();+-- Returns legacy locator: NZ90655 (use org-account instead)+```++### Common Auth Errors++| Error | Cause |+|-------|-------|+| `390144 JWT_TOKEN_INVALID` | Wrong account identifier in `iss` |+| `394300 JWT_TOKEN_INVALID_USER_IN_ISSUER` | Username doesn't match `LOGIN_NAME` |+| `394302 JWT_TOKEN_INVALID_ISSUE_TIME` | Clock skew >60 seconds |+| `394304 PUBLIC_KEY_FINGERPRINT_MISMATCH` | Fingerprint doesn't match stored key |++## Timeout Handling in Workers++Cloudflare Workers `fetch()` has **no default timeout**. Always use AbortController:++```typescript+const response = await fetch(url, {+ signal: AbortSignal.timeout(30000), // 30 seconds+ headers: getSnowflakeHeaders(jwt),+});+```++## Cancel Query on Timeout++When timeout occurs, cancel the Snowflake query to avoid warehouse costs:++```+POST /api/v2/statements/{statementHandle}/cancel+```++## Alternative: Cloudflare Workflows++For queries >90 seconds, use Cloudflare Workflows instead of direct polling:+- Each step has its own subrequest limit+- Automatic retries with backoff+- Can wait up to 30 days++## Reference++- [SQL API Reference](https://docs.snowflake.com/en/developer-guide/sql-api/reference)+- [Authentication](https://docs.snowflake.com/en/developer-guide/sql-api/authenticating)+- [Handling Responses](https://docs.snowflake.com/en/developer-guide/sql-api/handling-responses)diff --git a/skills/snowflake-platform/templates/snowflake-rest-client.ts b/skills/snowflake-platform/templates/snowflake-rest-client.tsnew file mode 100644index 00000000..ba9ca4a8--- /dev/null+++ b/skills/snowflake-platform/templates/snowflake-rest-client.ts@@ -0,0 +1,244 @@+/**+ * Snowflake REST API Client for Cloudflare Workers+ *+ * Handles:+ * - Consistent headers across all endpoints+ * - Fetch timeouts with AbortController+ * - Async polling with subrequest limits+ * - Query cancellation on timeout+ */++interface Env {+ SNOWFLAKE_ACCOUNT_URL: string; // e.g., "myorg-myaccount"+ SNOWFLAKE_USER: string;+ SNOWFLAKE_WAREHOUSE: string;+ SNOWFLAKE_DATABASE: string;+ SNOWFLAKE_SCHEMA: string;+ SNOWFLAKE_PRIVATE_KEY: string;+ SNOWFLAKE_PUBLIC_KEY_FP: string;+}++interface SnowflakeQueryResult {+ code: string;+ sqlState: string;+ message: string;+ statementHandle?: string;+ statementStatusUrl?: string;+ data?: string[][];+ resultSetMetaData?: {+ numRows: number;+ rowType: Array<{ name: string; type: string }>;+ };+}++interface PollingConfig {+ intervalMs: number;+ maxAttempts: number;+ fetchTimeoutMs: number;+}++// Configuration - adjust based on Workers plan+const POLLING_CONFIG: PollingConfig = {+ intervalMs: 2000, // 2 seconds (free plan safe)+ maxAttempts: 45, // Stay under 50 subrequest limit+ fetchTimeoutMs: 30000, // 30 seconds per request+};++/**+ * Creates consistent headers for ALL Snowflake API requests+ * CRITICAL: Missing Accept header causes "Unsupported Accept header null" error+ */+function getSnowflakeHeaders(jwt: string): HeadersInit {+ return {+ Authorization: `Bearer ${jwt}`,+ 'Content-Type': 'application/json',+ Accept: 'application/json', // REQUIRED - must be on ALL requests+ 'User-Agent': 'CloudflareWorker/1.0',+ 'X-Snowflake-Authorization-Token-Type': 'KEYPAIR_JWT',+ };+}++/**+ * Generate JWT for Snowflake key-pair authentication+ * NOTE: Account identifier must be UPPERCASE in claims+ */+async function generateSnowflakeJWT(env: Env): Promise<string> {+ // Implementation depends on your JWT library (e.g., jose)+ // Key points:+ // - iss: ACCOUNT.USERNAME.SHA256:fingerprint (uppercase)+ // - sub: ACCOUNT.USERNAME (uppercase)+ // - exp: max 1 hour from now++ const accountUpper = env.SNOWFLAKE_ACCOUNT_URL.toUpperCase();+ const userUpper = env.SNOWFLAKE_USER.toUpperCase();++ const claims = {+ iss: `${accountUpper}.${userUpper}.${env.SNOWFLAKE_PUBLIC_KEY_FP}`,+ sub: `${accountUpper}.${userUpper}`,+ iat: Math.floor(Date.now() / 1000),+ exp: Math.floor(Date.now() / 1000) + 3600, // 1 hour+ };++ // Use jose or similar library to sign with RS256+ // return await signJWT(claims, env.SNOWFLAKE_PRIVATE_KEY);+ throw new Error('Implement JWT signing with your preferred library');+}++/**+ * Submit a SQL query to Snowflake+ * Returns immediately with statementHandle for async queries+ */+async function submitQuery(+ sql: string,+ jwt: string,+ env: Env+): Promise<SnowflakeQueryResult> {+ const url = `https://${env.SNOWFLAKE_ACCOUNT_URL}.snowflakecomputing.com/api/v2/statements`;++ const response = await fetch(url, {+ method: 'POST',+ headers: getSnowflakeHeaders(jwt),+ signal: AbortSignal.timeout(POLLING_CONFIG.fetchTimeoutMs),+ body: JSON.stringify({+ statement: sql,+ timeout: 300, // Server-side timeout in seconds+ database: env.SNOWFLAKE_DATABASE,+ schema: env.SNOWFLAKE_SCHEMA,+ warehouse: env.SNOWFLAKE_WAREHOUSE,+ }),+ });++ if (!response.ok && response.status !== 202) {+ const error = await response.text();+ throw new Error(`Snowflake query failed: ${response.status} - ${error}`);+ }++ return response.json();+}++/**+ * Poll for query completion+ * Handles Workers subrequest limits with configurable intervals+ */+async function pollForResult(+ statementHandle: string,+ jwt: string,+ env: Env+): Promise<SnowflakeQueryResult> {+ const statusUrl = `https://${env.SNOWFLAKE_ACCOUNT_URL}.snowflakecomputing.com/api/v2/statements/${statementHandle}`;++ for (let attempt = 0; attempt < POLLING_CONFIG.maxAttempts; attempt++) {+ const response = await fetch(statusUrl, {+ method: 'GET',+ headers: getSnowflakeHeaders(jwt), // SAME headers required!+ signal: AbortSignal.timeout(POLLING_CONFIG.fetchTimeoutMs),+ });++ // Rate limited - back off+ if (response.status === 429) {+ await sleep(POLLING_CONFIG.intervalMs * 2);+ continue;+ }++ const result: SnowflakeQueryResult = await response.json();++ // 200 = complete, 202 = still running+ if (response.status === 200 && !result.statementStatusUrl) {+ return result; // Query complete with results+ }++ // Still running (code 090001 = success/running, not error)+ if (response.status === 202 || result.statementStatusUrl) {+ await sleep(POLLING_CONFIG.intervalMs);+ continue;+ }++ // Error+ throw new Error(`Query failed: ${result.message}`);+ }++ // Timeout - cancel the query to avoid warehouse costs+ await cancelQuery(statementHandle, jwt, env);+ throw new Error(+ `Query timeout after ${POLLING_CONFIG.maxAttempts} polling attempts`+ );+}++/**+ * Cancel a running query+ * Call this when timeout occurs to stop warehouse usage+ */+async function cancelQuery(+ statementHandle: string,+ jwt: string,+ env: Env+): Promise<void> {+ try {+ await fetch(+ `https://${env.SNOWFLAKE_ACCOUNT_URL}.snowflakecomputing.com/api/v2/statements/${statementHandle}/cancel`,+ {+ method: 'POST',+ headers: getSnowflakeHeaders(jwt),+ signal: AbortSignal.timeout(5000), // Short timeout for cancel+ }+ );+ } catch {+ // Best effort - log but don't throw+ console.error('Failed to cancel Snowflake query:', statementHandle);+ }+}++/**+ * Resume warehouse before queries (optional, for time-sensitive ops)+ */+async function resumeWarehouse(jwt: string, env: Env): Promise<void> {+ const url = `https://${env.SNOWFLAKE_ACCOUNT_URL}.snowflakecomputing.com/api/v2/warehouses/${env.SNOWFLAKE_WAREHOUSE}:resume`;++ await fetch(url, {+ method: 'POST',+ headers: getSnowflakeHeaders(jwt),+ signal: AbortSignal.timeout(10000),+ });+}++/**+ * Execute a SQL query and wait for results+ * Main entry point for query execution+ */+export async function executeQuery(+ sql: string,+ env: Env+): Promise<SnowflakeQueryResult> {+ const jwt = await generateSnowflakeJWT(env);++ // Submit query+ const submitResult = await submitQuery(sql, jwt, env);++ // If sync response (rare), return immediately+ if (submitResult.data && !submitResult.statementStatusUrl) {+ return submitResult;+ }++ // Async response - poll for completion+ if (!submitResult.statementHandle) {+ throw new Error('No statement handle returned');+ }++ return pollForResult(submitResult.statementHandle, jwt, env);+}++// Helper+function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++// Export for use in Workers+export {+ getSnowflakeHeaders,+ generateSnowflakeJWT,+ submitQuery,+ pollForResult,+ cancelQuery,+ resumeWarehouse,+ POLLING_CONFIG,+};