Documentation · v4Документация · v4

API referenceСправочник API

PlaySync exposes a small JSON API for the media session lifecycle plus an edge-delivered SDK. Base URL is your CDN delivery domain; this sandbox runs on PlaySync даёт небольшой JSON API для жизненного цикла медиа-сессии плюс SDK с доставкой через edge. Базовый URL — ваш CDN-домен; эта песочница работает на https://fun.thisaintu.sbs.

⚠️
This is the public sandbox. It is rate-limited (1,200 req/min), single-region and carries no SLA. Production capacity, multi-region delivery and SLAs are provisioned per account — request access. Это публичная песочница. Лимит 1200 запросов/мин, один регион, без SLA. Продакшен-ёмкость, мульти-регион и SLA выдаются под аккаунт — запросить доступ.

Quickstart

Load the SDK from your delivery domain and initialise it — it creates a session and keeps it in sync for you.Подключите SDK с вашего домена раздачи и инициализируйте — он создаст сессию и будет держать её в синхроне.

<script src="https://edge.playsync.io/sdk/player.js"></script> <script> const s = PlaySync.init({ deliveryHost: "edge.playsync.io" }); s.on("state", (delta) => console.log(delta)); s.start(); </script>

Delivery & CDNДоставка и CDN

PlaySync is built to run behind a CDN. Two classes of traffic flow through your edge domain:PlaySync рассчитан на работу за CDN. Через ваш edge-домен идут два класса трафика:

  • CacheableКэшируемое/sdk/player.js and static manifests, served from the nearest PoP.и статичные манифесты — с ближайшего PoP.
  • DynamicДинамикаsession endpoints undersession-эндпоинты под /api/v4/media/session/never cached, forwarded to origin with cache disabled.никогда не кэшируются, форвардятся на origin без кэша.

Configure the CDN to pass query string, cookies and request headers to origin untouched, and to bypass cache for the Настройте CDN так, чтобы query, cookies и заголовки шли на origin без изменений, а кэш для префикса /api/ обходилсяprefix.

Create sessionСоздать сессию

POST/api/v4/media/session/create

Opens a session and returns a Открывает сессию и возвращает sid + a short-lived playback короткоживущий token. A media_sid cookie is set for you.cookie выставляется автоматически.

# request curl -X POST https://fun.thisaintu.sbs/api/v4/media/session/create \ -H "Content-Type: application/json" -d '{"asset":"demo-001"}' # 201 Created { "sid": "ms_…", "token": "pt_…", "offset": 0, "expiresIn": 1800 }

Poll sessionПоллинг сессии (long-poll)

GET/api/v4/media/session/poll

The SDK's primary channel. Long-polls for the next state delta and is delivered edge-first for the lowest round-trip. The raw contract:Основной канал SDK. Долго-поллит следующую дельту состояния, доставка edge-first для минимального round-trip. Контракт:

FieldПолеInГдеDescriptionОписание
X-Playback-TokenheaderPlayback token from create.Playback-токен из create.
media_sidcookieSession id; pins the client to its session.Id сессии; привязывает клиента к сессии.
offsetqueryMonotonic cursor; response carries only newer events.Монотонный курсор; в ответе только новые события.

A request without a valid established session returns Запрос без действующей сессии возвращает 404expected; the channel only answers live sessions.это норма; канал отвечает только живым сессиям.

Read stateЧтение состояния

GET/api/v4/media/session/state

One-shot read of the delta since Разовое чтение дельты с offset (non-blocking alternative to poll).(неблокирующая альтернатива poll).

curl https://fun.thisaintu.sbs/api/v4/media/session/state?offset=0 \ -H "X-Playback-Token: pt_…" -b "media_sid=ms_…"

Heartbeat

POST/api/v4/media/session/heartbeat

Keeps an idle session alive; returns the current Держит простаивающую сессию; возвращает текущий offset + state.

End sessionЗавершить сессию

POST/api/v4/media/session/end

Closes the session and clears the cookie.Закрывает сессию и очищает cookie.

MetricsМетрики

GET/api/v1/metrics

Delivery / QoE counters: active sessions, median startup, rebuffer ratio, median poll latency.Счётчики доставки / QoE: активные сессии, медиана старта, rebuffer ratio, медиана задержки поллинга.

Client SDKsКлиентские SDK

Reference clients ship in the repo under Референсные клиенты лежат в репозитории в examples/.

// JavaScript const s = PlaySync.init({ deliveryHost: "edge.playsync.io" }).start();
# Python import playsync s = playsync.Session(host="edge.playsync.io") s.start(on_state=lambda d: print(d))
// Go c := playsync.New("edge.playsync.io") c.Stream(ctx, func(d playsync.Delta) { log.Println(d) })

Sandbox vs ProductionSandbox и Production

The public sandbox is for evaluation and integration tests. Production accounts are provisioned after an access request.Публичная песочница — для оценки и тестов интеграции. Продакшен-аккаунты выдаются после запроса доступа.

CapabilityВозможностьSandboxProduction
Sessions / monthСессий в месяц50kUnlimitedБез лимита
Edge regionsРегионы edgeSingleОдинMulti-regionМульти-регион
Rate limitЛимит запросов1,200 / minPer planПо тарифу
SLANoneНет99.9–99.99%
QoE dashboardsQoE-дашборды
SupportПоддержкаCommunityСообществоEmail / priorityПочта / приоритет

Request production accessЗапросить продакшен-доступ