shinyorg/shiny/shiny-data-sync

Claude Code and agent skill by shinyorg/shiny

Trust tier 2
  • community
LLM review pending
Source check pending

Checking that the SKILL.md file is still in the repository.

Guide for generating code that uses Shiny.Data.Sync for reliable, background-capable bidirectional JSON sync over HTTP on iOS, Android, Windows, Linux, macOS, and Blazor WASM

Install

npx vskill@latest install shinyorg/shiny/shiny-data-sync

SKILL.md

The same SKILL.md was published earlier as shinyorg/shiny/shiny-data-sync.

Shiny Data Sync

Reliable, background-capable bidirectional JSON sync between a mobile/desktop app and an HTTP backend. Mirrors the platform-tier guarantees of Shiny.Net.Http (NSURLSession on Apple, Foreground Service on Android, HttpClient fallback elsewhere), but for structured records rather than files.

Provides an outbox for queued local changes (Create/Update/Delete with JSON payloads), an inbox for delta pulls from the server, retry with exponential backoff, pluggable conflict resolution, per-endpoint batching, and AOT-compatible JSON via JsonTypeInfo.

When to Use This Skill

Use this skill when the user needs to:

  • Sync app entities to a REST backend reliably, even when offline or backgrounded
  • Build an offline-first feature that eventually consistent-syncs to the server
  • Queue Create/Update/Delete operations that must survive app kill / device reboot
  • Pull server-side changes on a schedule (delta sync)
  • Resolve sync conflicts (HTTP 409 / 412) with custom merge logic
  • Batch multiple queued operations into a single server round-trip
  • Persist a per-endpoint cursor for delta pulls

Do not use this skill for: large file uploads/downloads (use shiny-http-transfers), realtime data streams (use SignalR/MQTT), or push-driven sync (use shiny-push to trigger PullNow).

Library Overview

ItemValue
NuGetShiny.Data.Sync (one package everywhere - its net11.0 build includes Blazor WASM)
NamespaceShiny.Data.Sync
PlatformsiOS / tvOS / Mac Catalyst (NSURLSession background, both outbox upload + inbox download); Android (Foreground Service + HttpClient); Windows / Linux / base .NET (HttpClient + connectivity loop); Blazor WASM (HttpClient + LocalStorage)
DI Setupservices.AddDataSync<TDelegate>(builder => ...) on all native platforms (auto-picks NSURLSession / Foreground Service / HttpClient based on TFM), services.AddBlazorDataSync<TDelegate>(...) on Blazor WASM (same package; Shiny.Data.Sync.Blazor no longer exists)

Setup

1. Define an Entity

Implement ISyncEntity on any record you want to sync:

csharp
using Shiny.Data.Sync;
public record TodoItem(string Identifier, string Title, bool Completed) : ISyncEntity;
2. Register Services

In MauiProgram.cs (reflection-friendly path):

csharp
using Shiny;
builder.Services.AddDataSync<MyDataSyncDelegate>(opts =>
{
opts.RegisterEndpoint<TodoItem>("https://api.example.com/todos");
opts.RegisterEndpoint<Project>("https://api.example.com/projects", ep =>
{
// -- Direction --
ep.Direction = SyncDirection.Both; // or PullOnly / PushOnly
// -- Network policy --
ep.UseMeteredConnection = false; // wait for WiFi
ep.Batch = true; // coalesce ops per round-trip
ep.MaxAttempts = 8; // retry transient failures up to 8x
ep.RetryBaseDelay = TimeSpan.FromSeconds(3);
ep.TreatMissingAsDeleted = true; // default: 404/410 on a DELETE completes it as sent
// -- Conflicts --
ep.DefaultConflictPolicy = ConflictPolicy.ServerWins;
// -- Inbox throttle / scheduling --
// null = manual only: SyncJob/PullAll skip this endpoint; only PullNow<T> pulls it
// TimeSpan.Zero = always pull on every scheduled pass (the default applied at registration)
// positive = throttle: SyncJob/PullAll skip while within the window; PullNow bypasses
ep.MinPullInterval = TimeSpan.FromMinutes(5);
// -- Per-verb URL overrides (optional) --
ep.PullUrl = "https://api.example.com/projects/feed"; // GET different URL on pull
ep.BatchUrl = "https://api.example.com/projects/bulk"; // POST batched ops elsewhere
ep.CursorParameter = "updatedSince"; // default "since"
// -- Tombstones (server-side delete stream) --
ep.TombstoneUrl = "https://api.example.com/projects/deleted";
ep.TombstoneCursorParameter = "since";
// -- Soft-delete / expiry predicates --
ep.SoftDeletePredicate = entity => entity is Project p && p.IsArchived;
ep.ExpiryPredicate = entity => entity is Project p && p.OwnerId == null;
// -- Per-endpoint request hook (after ISyncInterceptor) --
ep.OnBeforeSend = req =>
{
req.Headers.Add("X-Trace-Id", Guid.NewGuid().ToString("N"));
return Task.CompletedTask;
};
});
});
// Global auth — runs before every endpoint's OnBeforeSend
builder.Services.AddSyncInterceptor<MyAuthInterceptor>();
// Centralize base address / Polly handlers on the named client
builder.Services.AddHttpClient(RestSyncTransport.HttpClientName, c =>
c.BaseAddress = new Uri("https://api.example.com")
);
Native AOT / trimmed builds

All serialization runs through Shiny.Json.Default (the shared ISerializer from Shiny.Extensions.Serialization). Add the entity type to a context decorated with [ShinyJsonContext] — a source-generated module initializer wires it into the shared chain before any code runs:

csharp
[ShinyJsonContext]
[JsonSerializable(typeof(TodoItem))]
[JsonSerializable(typeof(Project))]
public partial class AppJsonContext : JsonSerializerContext;

The same context covers every endpoint that uses these types — no per-endpoint plumbing. To customize options globally use services.ConfigureJsonSerializer(opts => ...) from Shiny.Extensions.Serialization.

3. Implement the Delegate
csharp
using Shiny.Data.Sync;
public class MyDataSyncDelegate : IDataSyncDelegate
{
public Task OnSent(SyncOperation op, string? responseBody)
{
// Server accepted the op. responseBody may contain a server-assigned id, new ETag, etc.
return Task.CompletedTask;
}
public Task OnError(SyncOperation op, int statusCode, Exception ex)
{
// Op exhausted its retry budget. Persist to a dead-letter store or notify the user.
return Task.CompletedTask;
}
public Task OnReceived(SyncReceivedItem item)
{
// The engine already deserialized item.Entity using the endpoint's JsonTypeInfo
// or JsonOptions. RawPayload is also available for custom handling.
if (item.Entity is TodoItem todo)
myLocalStore.Apply(todo, item.Verb);
else if (item.Verb == SyncVerb.Delete && item.EntityIdentifier is { } id)
myLocalStore.Delete(id); // tombstones carry no entity - only the id
return Task.CompletedTask;
}
public Task<ConflictResolution> OnConflict(SyncOperation op, string remotePayload)
{
// The server already has a newer version. Decide what to do.
return Task.FromResult(ConflictResolution.AcceptRemote);
}
}

Common Tasks

Queue an outbox operation
csharp
public class TodosService(IDataSyncManager sync)
{
public Task CreateTodo(TodoItem item) => sync.Queue(SyncVerb.Create, item);
public Task UpdateTodo(TodoItem item) => sync.Queue(SyncVerb.Update, item);
public Task DeleteTodo(TodoItem item) => sync.Queue(SyncVerb.Delete, item);
}
Force a pull (pull-to-refresh)
csharp
public Task RefreshTodos(IDataSyncManager sync, CancellationToken ct)
=> sync.PullNow<TodoItem>(ct);
Observe outbox + inbox progress
csharp
// Typed events for fine-grained subscribers
sync.PendingCountChanged += (s, count) => StatusLabel.Text = $"{count} pending";
sync.UpdateReceived += (s, result) =>
{
if (result.State == SyncOperationState.Error)
ShowToast($"Sync failed: {result.Exception?.Message}");
};
sync.PullCompleted += (s, c) =>
{
if (c.Error != null) ShowToast($"Pull failed for {c.EndpointKey}: {c.Error.Message}");
else if (c.ItemsReceived > 0) ShowToast($"{c.ItemsReceived} new {c.EndpointKey} items");
};
// Unified Activity stream — covers every lifecycle moment
sync.Activity += (s, evt) =>
{
Console.WriteLine($"{evt.Type} {evt.EndpointKey} items={evt.ItemCount} status={evt.StatusCode}");
};

Activity fires SyncEvent records for: OutboxQueued, OutboxStarted, OutboxSent, OutboxFailed, OutboxConflict, OutboxRetryScheduled, OutboxCanceled, InboxPullStarted, InboxItemReceived, InboxPullCompleted, InboxPullFailed, TombstonesApplied.

Cancel queued work
csharp
await sync.Cancel(operationId); // one operation
await sync.CancelAll<TodoItem>(); // everything for one endpoint
await sync.CancelAll(); // entire outbox (in-flight inbox pulls are left alone)

Platform Behavior

PlatformOutbox transportInbox transportSurvives app kill?
iOS / tvOS / Mac CatalystBackground NSURLSession upload taskBackground NSURLSession download taskYes (both directions)
AndroidForeground Service + HttpClientHttpClient (in-process)Outbox yes (notification visible while syncing); inbox no
Windows / Linux / base .NETHttpClient + connectivity loopHttpClient + connectivity loopNo — resumes on next launch
Blazor WASMHttpClient + LocalStorageHttpClient + LocalStorageNo — syncs while tab is open

On iOS the JSON payload is serialized to a temp file (background NSURLSessions require file-backed uploads); the temp file is cleaned up when the operation completes or fails. The same background NSUrlSession carries both upload and download tasks (HttpMaximumConnectionsPerHost = 4).

A regained network connection on the HttpClient platforms (Windows / Linux / desktop) automatically triggers an outbox drain and a full PullAll via the IConnectivity.Changed event.

Retry policy

Every endpoint has MaxAttempts (default 5) and RetryBaseDelay (default 2s). Transient failures — HttpStatusCode 0 (network down), 5xx, 408, 429 — schedule a retry at baseDelay * 2^(attempts-1) capped at 60s. The retry timestamp is persisted on the SyncOperation as NextAttemptAt, so a process restart resumes the wait window correctly. After MaxAttempts, the op is handed to IDataSyncDelegate.OnError and removed from the outbox (the delegate can re-queue if it wants).

DELETE answered `404` / `410`. With TreatMissingAsDeleted (default true) a 404 Not Found or 410 Gone on a Delete op completes it as sent: OnSent runs (response body null) and the op is reported Completed / OutboxSent with that status code. The entity is gone either way - this covers a retried DELETE whose first try succeeded, and a coalesced Create + Delete whose Create may never have landed. It applies on every platform (single sends, batch items, and Apple upload tasks). Set it to false only when your API returns 404 on DELETE for something else; those ops then fail permanently through OnError as before. Other verbs are unaffected - a 404 on an Update still fails.

Ordering is per entity: while an op waits out its backoff, later ops for the same EntityIdentifier wait too, so the server always sees an entity's changes in the order they were queued. The outbox loop keeps running through backoff windows (it no longer stops until the next Queue/app start). On iOS / Mac Catalyst an op waiting for a retry has no native task; if the app is killed during the wait, Start() re-sends it on the next launch, and Cancel(id) / CancelAll() cancel such ops too. Start() also re-sends any op left Pending / InProgress with no retry marker and no native task (stranded by older versions) - with no task it can't be in flight, so this never duplicates a request.

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewNot runA model review is scheduled for the next rescan.

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
1,593
Repository forks
253
7-day trend score
0

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/shinyorg/shiny/shiny-data-sync/badge)](https://verified-skill.com/skills/shinyorg/shiny/shiny-data-sync)

Something wrong with this skill or its page? Tell us.