ブラウザクライアント
ネイティブの WebSocket API でブラウザから接続できます。ライブラリは不要です。このページでは、サブスクライブし、接続を維持し、再接続する完全なクライアントを示します。
Web ページ内のキーは、ページを開いた全員に見えます。ブラウザは、取り消せるキーを使った短いテストや社内ツールにだけ使ってください。公開サイトでは、キーを秘密に保てる自社のサーバーから接続し、記事をユーザーに転送してください。
サーバーのクライアントとの違い
- キーは URL に入れます。 ブラウザは WebSocket にヘッダーを設定できないため、
x-api-keyヘッダーの代わりに?apiKey=を使います。 - 接続が拒否された理由はわかりません。 ブラウザは拒否された接続の HTTP ステータスを見せません。ソケットは開く前にコード
1006で閉じるだけです。間違ったキー、WebSockets を含まないプラン、接続数の上限はどれも同じに見えます。何回か続けて失敗したら止めて、ダッシュボードでキーとプランを確認してください。 - それ以外はすべて同じです。 サブスクライブメッセージを送り、25 秒ごとに ping を送り、制御フレームを処理し、必要に応じて再接続します。ライフサイクルと制限を参照してください。
接続 URL
| ストリーム | URL |
|---|---|
| エンリッチ | wss://wss.finlight.me?apiKey=YOUR_API_KEY |
| Raw | wss://wss.finlight.me/raw?apiKey=YOUR_API_KEY |
任意のクエリパラメータ: takeover=true は上限に達しているときに最も古くなった接続を置き換え、clientVersion=... はクライアントにラベルを付けます。値は URL エンコードしてください。接続を参照してください。
WEBSOCKETBrowser
完全な例
このクライアントは次のことを行います:
- URL にキーを入れて接続し、サブスクライブメッセージを送ります。
- 25 秒ごとに ping を送り、60 秒間 pong が届かなければ再接続します。
- 1 秒から 30 秒まで延びる待ち時間で再接続し、pong か記事を受け取ったら待ち時間をリセットします。
- 5 回続けて接続が拒否された場合、
VALIDATION_FAILEDの後、connection_limitのプリエンプションの後に停止します。 quota_exceededのプリエンプションの後は 1 時間待ちます。- 再接続後の初回プッシュも含め、重複したフレームを取り除きます。
- 2 時間の上限の前、115 分後に再接続します。これにより短い途切れが生じます。すべての記事が必要な場合は REST で埋めてください。ライフサイクルと制限を参照してください。
v3 のフレームと、最初のサブスクライブの前にサーバーが送る v2 の制御フレームの両方を読み取ります。
ブラウザクライアント
WEBSOCKET
wss://wss.finlight.meconst API_KEY = 'YOUR_API_KEY' // tests only, see the note above
const BASE_URL = 'wss://wss.finlight.me' // raw stream: 'wss://wss.finlight.me/raw'
const SUBSCRIBE = {
payloadVersion: 3,
query: 'ticker:AMD',
language: 'en',
include: ['companies', 'events'], // leave out on the raw stream
includeUpdates: true,
clientNonce: crypto.randomUUID(),
}
function startStream({ onArticle, onStatus = console.log }) {
let ws
let pingTimer
let watchdog
let rotateTimer
let delay = 1000
let refusedInARow = 0
let stopped = false
const seen = new Set()
const resetWatchdog = () => {
clearTimeout(watchdog)
watchdog = setTimeout(() => ws.close(4000, 'no pong'), 60_000)
}
const stop = (why) => {
stopped = true
onStatus(`stopped: ${why}`)
ws?.close(1000)
}
const scheduleReconnect = (waitMs) => {
onStatus(`reconnecting in ${Math.round(waitMs / 1000)} s`)
setTimeout(connect, waitMs)
}
function connect() {
if (stopped) return
let opened = false
let nextWait = null // set by frames that need a special wait
ws = new WebSocket(`${BASE_URL}?apiKey=${encodeURIComponent(API_KEY)}`)
ws.onopen = () => {
opened = true
refusedInARow = 0
ws.send(JSON.stringify(SUBSCRIBE))
pingTimer = setInterval(() => ws.send(JSON.stringify({ action: 'ping', t: Date.now() })), 25_000)
rotateTimer = setTimeout(() => {
nextWait = 0
ws.close(1000, 'rotate')
}, 115 * 60_000)
resetWatchdog()
}
ws.onmessage = (message) => {
const frame = JSON.parse(message.data)
const name = frame.event ?? frame.action // v2 control frames use "action"
const data = frame.data ?? frame
switch (name) {
case 'article.created':
case 'article.updated': {
delay = 1000
resetWatchdog()
const key = `${name}|${data.id}|${JSON.stringify(data)}`
if (seen.has(key)) return
seen.add(key)
if (seen.size > 5000) seen.delete(seen.values().next().value)
onArticle(name, data)
break
}
case 'connection.pong':
case 'pong':
delay = 1000
resetWatchdog()
break
case 'connection.admitted':
case 'admit':
onStatus(`admitted, lease ${data.leaseId}`)
break
case 'connection.preempted':
case 'preempted':
if (data.reason === 'connection_limit') stop('another connection took over')
else nextWait = 60 * 60_000 // quota_exceeded: try again in one hour
break
case 'connection.error':
if (data.code === 'VALIDATION_FAILED') stop(`subscribe rejected: ${JSON.stringify(data.details)}`)
else onStatus(`server error ${data.code}: ${data.message}`)
break
default:
// "error" in v2 form, or an event this client does not know yet
onStatus(`ignored frame ${name}`)
}
}
ws.onclose = (event) => {
clearInterval(pingTimer)
clearTimeout(watchdog)
clearTimeout(rotateTimer)
if (stopped) return
if (!opened && ++refusedInARow >= 5) {
stop('connection refused 5 times: check the API key and your plan')
return
}
if (event.code === 1008) {
stop('closed by the server with code 1008')
return
}
const wait = nextWait ?? delay
delay = Math.min(delay * 2, 30_000)
scheduleReconnect(wait)
}
}
connect()
return { close: () => stop('closed by you') }
}
// Usage
const stream = startStream({
onArticle: (event, article) => console.log(event, article.id, article.title),
})
// later: stream.close()
表示されるメッセージ
| フレーム | 意味 |
|---|---|
connection.admitted | 最初のサブスクライブが届きました。サーバーがサブスクライブをチェックする前に送られます。 |
article.created | 一致する新しい記事。サブスクライブ直後の最初のものは、既存の一致のうち最新のものです。 |
article.updated | 一致する記事への変更。includeUpdates: true の場合のみ。 |
connection.pong | ping への応答。 |
connection.preempted | サーバーがこの接続を閉じます。reason を確認してください。 |
connection.error | メッセージに問題があります。code を確認してください。 |
{"action": ...} | 最初のサブスクライブの前に送られる、v2 形式の制御フレーム。 |
完全な一覧とエラーコードはフレームを参照してください。
次のステップ
- サブスクライブ: すべてのサブスクライブフィールド。
- Raw ストリーム: より速い骨格のストリーム。
- ライフサイクルと制限: ping、ローテーション、クォータ、欠落の補完。