본문으로 건너뛰기
cccskills
무료GitHub에 공개

stale-cache-external-service-recovery

Handle stale local cache when external service loses/resets data. Use when: (1) Token refresh fails with "not found" or 404 errors, (2) Cached identifiers (pubkeys, user IDs) don't exist on external service anymore, (3) External service was reset/migrated but local cache has old values. Pattern: detect 404 specifically, delete stale cache entry, recreate on external service, update cache with new values. Complements local-cache-idempotency-fallback skill.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

설치 방법 보기

포함된 파일(1)

  • SKILL.md5.5 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Stale Cache Recovery When External Service Loses Data

Problem

When using your database as a cache/idempotency layer (see local-cache-idempotency-fallback), a new failure mode emerges: the external service loses or resets its data, but your cache still has the old values. Operations fail with misleading errors because the cached identifiers don't exist on the external service anymore.

Context / Trigger Conditions

  • Token refresh fails with 404 "User with pubkey/id not found"
  • Operations fail with "Invalid or expired token" but the real issue is missing user
  • External service was reset, migrated, or lost data
  • Cached identifiers (pubkeys, API keys, user IDs) are valid in cache but not on service
  • Error message is misleading - suggests token issue when it's actually a missing resource

Solution

Detect the specific "not found" case and handle it separately from other errors:

if (cached) {
  pubkey = cached.pubkey;
  token = cached.token;

  try {
    // Try to refresh/validate the cached credentials
    const freshToken = await externalApi.getTokenByPubkey(pubkey);
    token = freshToken;
    console.log(`Pubkey: ${pubkey} (token refreshed)`);
  } catch (error) {
    const errMsg = error instanceof Error ? error.message : String(error);

    // CRITICAL: Detect "not found" specifically - cache is stale
    if (errMsg.includes("not found") || response.status === 404) {
      console.log(`Cached identifier not on external service, recreating...`);

      // 1. Delete stale cache entry
      await db.deleteUser(userId);

      // 2. Create fresh resource on external service
      const result = await externalApi.createUser(userId, username);
      pubkey = result.pubkey;
      token = result.token;
      console.log(`Pubkey: ${pubkey} (recreated)`);

      // 3. Cache new values
      await db.saveUser({ userId, pubkey, token });
    } else {
      // Other error (e.g., user claimed account, rate limit) - can't proceed
      console.log(`Refresh failed: ${errMsg}`);
      continue; // or throw
    }
  }
}

Key Pattern

  1. Attempt normal refresh first: Try to validate/refresh cached credentials
  2. Detect 404 specifically: Check for "not found" in error message or 404 status
  3. Delete stale entry: Remove the invalid cache entry before recreating
  4. Recreate on external: Create fresh resource with same input identifiers
  5. Update cache: Store new values for future runs
  6. Distinguish from other errors: Only handle 404; other errors may need different handling

Verification

  1. Simulate external service data loss (or clear its database)
  2. Run script with stale local cache
  3. Should see "recreating" message, not crash with 401/404
  4. New values cached and used for subsequent operations
  5. Script completes successfully

Example

Real-world application - Keycast pubkey cache recovery:

const cached = await pgDb.getImportedUser(creator.user_id);
let pubkey: string;
let token: string;

if (cached) {
  pubkey = cached.pubkey;
  token = cached.token;

  try {
    const freshToken = await keycast.getTokenByPubkey(pubkey);
    token = freshToken;
    await pgDb.saveImportedUser({ ...cached, token: freshToken });
    console.log(`Pubkey: ${pubkey} (token refreshed)`);
  } catch (refreshError) {
    const errMsg = refreshError instanceof Error ? refreshError.message : String(refreshError);

    if (errMsg.includes("not found")) {
      // Keycast doesn't have this pubkey - cache is stale
      console.log(`Cached pubkey not on Keycast, recreating user...`);

      // Delete stale entry
      await pgDb.deleteImportedUser(creator.user_id);

      // Create fresh user
      const result = await keycast.createPreloadedUser(
        creator.user_id,
        username,
        displayName
      );
      pubkey = result.pubkey;
      token = result.token;
      console.log(`Pubkey: ${pubkey} (recreated)`);

      // Cache new account
      await pgDb.saveImportedUser({
        vine_user_id: creator.user_id,
        username: creator.username,
        pubkey,
        token,
        events_published: 0,
      });
    } else {
      // Other error - user may have claimed account, can't proceed
      console.log(`Token refresh failed: ${errMsg}`);
      console.log(`Skipping ${creator.username} - cannot sign events`);
      continue;
    }
  }
}

Notes

  • This complements local-cache-idempotency-fallback - use both together
  • The misleading error chain: 404 "not found" → continue with stale token → 401 "invalid token"
  • Always delete before recreate to avoid accumulating orphan cache entries
  • Consider logging which entries were stale for debugging/monitoring
  • If external service is frequently losing data, investigate root cause
  • The new pubkey will be different from the old one - downstream systems may need updates

Related Skills

  • local-cache-idempotency-fallback: The base pattern this skill extends
  • Database retry logic for connection resets (separate concern)

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Fix ArgoCD ExternalSecret deployment failing with "namespace X is not permitted in project Y". Use when: (1) ExternalSecret shows OutOfSync in ArgoCD but won't sync, (2) ArgoCD application status shows "namespace X is not permitted in project 'infrastructure'", (3) ExternalSecret targets a namespace managed by a different ArgoCD project, (4) Using apps-of-apps pattern with separate infrastructure and application projects.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

divinevideo/divine-mobile2652026년 10월 23일 업데이트

Art direction for any content — reads text, PDF, Word, HTML, PPT, then proposes 2-3 creative directions with photography style, mood, and visual language. After selection, generates AI image prompts and visual briefs section-by-section. Use when the user shares content and needs visual direction, image sourcing, or creative direction for any material.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

divinevideo/divine-mobile2652026년 10월 23일 업데이트

Fix "Null check operator used on a null value" errors when an object is set to null during an async await. Use when: (1) Object reference is nullified while awaiting, (2) Code accesses object with ! after await returns, (3) Cancel/dispose operations run concurrently with async operations on same object. Solution: capture local reference before await.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

divinevideo/divine-mobile2652026년 10월 23일 업데이트

Add custom metadata headers (x-amz-meta-*) to AWS v4 signed requests for GCS S3-compatible API. Use when: (1) Adding custom metadata to GCS uploads via S3 API, (2) Getting signature mismatch errors after adding new headers, (3) x-amz-meta-* headers being ignored or causing 403 errors. Custom headers MUST be included in canonical headers and signed headers list.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

divinevideo/divine-mobile2652026년 10월 23일 업데이트

Fix password/secret authentication failures caused by trailing newlines when creating Google Cloud secrets (or similar) with bash here-strings. Use when: (1) Password authentication fails with correct password, (2) Secret created with `<<< "value"` syntax, (3) Error like "password authentication failed" or "invalid token" despite correct value. Bash here-strings (`<<<`) add a trailing newline that corrupts secrets.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

divinevideo/divine-mobile2652026년 10월 23일 업데이트

Fix silent video/media processing failures caused by URL extraction code that filters on file extensions (.mp4, .webm, .webp). Use when: (1) Media moderation, transcoding, or analysis silently skips files from Blossom or content-addressed storage servers, (2) URL extraction from Nostr event tags (imeta, r tags) drops URLs without recognized extensions, (3) CDN fallback URLs append .mp4 but the actual server uses extensionless content-addressed paths like /{sha256}. Common in Nostr video events (kind 34236) where different clients use different URL formats.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

divinevideo/divine-mobile2652026년 10월 23일 업데이트

divinevideo의 스킬 모두 보기

이 스킬의 문제 신고