feat: live-sync-client im frontend
- WebSocket-Verbindung nach dem Login, Wiederverbindung mit Backoff (1-30 s) - nach jeder Wiederverbindung wird die Liste neu geladen - sofortige Wiederverbindung bei Rückkehr in den Vordergrund (iOS) und online-Event - Watchdog erkennt tote Verbindungen nach 75 s ohne Nachricht - Clip-Store übernimmt nur neuere Versionen; Logout leert die lokalen Daten - Statuspunkt im Header: live / verbinde / offline Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0d89399090
commit
e20af699dc
5 files changed
+230
-3
No files matched your search
@@ -1,10 +1,28 @@
|
||||
<script setup lang="ts">
|
||||
import { watch } from 'vue'
|
||||
import { RouterView } from 'vue-router'
|
||||
|
||||
import AppHeader from '@/components/AppHeader.vue'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useClipsStore } from '@/stores/clips'
|
||||
import { useSyncStore } from '@/stores/sync'
|
||||
|
||||
const auth = useAuthStore()
|
||||
const clips = useClipsStore()
|
||||
const sync = useSyncStore()
|
||||
|
||||
// Live sync runs while someone is logged in; local data is dropped on logout or user switch
|
||||
watch(
|
||||
() => auth.user?.id ?? null,
|
||||
(userId, previousId) => {
|
||||
if (previousId !== undefined && userId !== previousId) {
|
||||
sync.stop()
|
||||
clips.reset()
|
||||
}
|
||||
if (userId !== null) sync.start()
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -18,6 +18,11 @@ export function setUnauthorizedHandler(handler: UnauthorizedHandler): void {
|
||||
onUnauthorized = handler
|
||||
}
|
||||
|
||||
/** Report an expired or revoked session detected outside of fetch (e.g. WebSocket close). */
|
||||
export function notifyUnauthorized(): void {
|
||||
onUnauthorized?.()
|
||||
}
|
||||
|
||||
function readCookie(name: string): string | null {
|
||||
const match = document.cookie.split('; ').find((c) => c.startsWith(`${name}=`))
|
||||
return match ? decodeURIComponent(match.slice(name.length + 1)) : null
|
||||
|
||||
@@ -2,8 +2,16 @@
|
||||
import { RouterLink, useRouter } from 'vue-router'
|
||||
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useSyncStore } from '@/stores/sync'
|
||||
|
||||
const auth = useAuthStore()
|
||||
const sync = useSyncStore()
|
||||
|
||||
const STATUS_LABELS = {
|
||||
live: 'Live-Sync aktiv',
|
||||
connecting: 'Verbinde …',
|
||||
offline: 'Offline',
|
||||
} as const
|
||||
const router = useRouter()
|
||||
|
||||
async function logout(): Promise<void> {
|
||||
@@ -14,7 +22,16 @@ async function logout(): Promise<void> {
|
||||
|
||||
<template>
|
||||
<header class="header">
|
||||
<RouterLink to="/" class="brand">LAN-Clipboard</RouterLink>
|
||||
<RouterLink to="/" class="brand">
|
||||
LAN-Clipboard
|
||||
<span
|
||||
class="sync-dot"
|
||||
:class="sync.status"
|
||||
role="status"
|
||||
:title="STATUS_LABELS[sync.status]"
|
||||
:aria-label="STATUS_LABELS[sync.status]"
|
||||
></span>
|
||||
</RouterLink>
|
||||
<nav class="nav">
|
||||
<RouterLink to="/account">Konto</RouterLink>
|
||||
<RouterLink v-if="auth.isAdmin" to="/admin/users">Benutzer</RouterLink>
|
||||
@@ -39,11 +56,37 @@ async function logout(): Promise<void> {
|
||||
}
|
||||
|
||||
.brand {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
color: var(--text);
|
||||
font-weight: 700;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.sync-dot {
|
||||
width: 0.6rem;
|
||||
height: 0.6rem;
|
||||
border-radius: 50%;
|
||||
background: var(--muted);
|
||||
transition: background-color 0.3s;
|
||||
}
|
||||
|
||||
.sync-dot.live {
|
||||
background: var(--ok);
|
||||
}
|
||||
|
||||
.sync-dot.connecting {
|
||||
background: var(--muted);
|
||||
animation: pulse 1.2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
50% {
|
||||
opacity: 0.3;
|
||||
}
|
||||
}
|
||||
|
||||
.nav {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -24,19 +24,33 @@ export const useClipsStore = defineStore('clips', () => {
|
||||
const total = ref(0)
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
const loaded = ref(false)
|
||||
|
||||
/** Insert or replace a clip locally (also the entry point for live sync later). */
|
||||
/**
|
||||
* Insert or replace a clip locally. Used for API responses and live-sync events;
|
||||
* an older version never overwrites a newer one, whatever arrives first.
|
||||
*/
|
||||
function upsert(clip: Clip): void {
|
||||
const index = items.value.findIndex((c) => c.id === clip.id)
|
||||
if (index === -1) {
|
||||
items.value.push(clip)
|
||||
total.value += 1
|
||||
} else {
|
||||
} else if (items.value[index]!.version <= clip.version) {
|
||||
items.value[index] = clip
|
||||
} else {
|
||||
return
|
||||
}
|
||||
items.value.sort(compareClips)
|
||||
}
|
||||
|
||||
/** Forget everything, e.g. on logout so the next user on this device sees nothing. */
|
||||
function reset(): void {
|
||||
items.value = []
|
||||
total.value = 0
|
||||
error.value = null
|
||||
loaded.value = false
|
||||
}
|
||||
|
||||
function removeLocal(id: number): void {
|
||||
const before = items.value.length
|
||||
items.value = items.value.filter((c) => c.id !== id)
|
||||
@@ -50,6 +64,7 @@ export const useClipsStore = defineStore('clips', () => {
|
||||
const page = await api.get<ClipList>(`/clips?limit=${PAGE_SIZE}&offset=0`)
|
||||
items.value = page.items
|
||||
total.value = page.total
|
||||
loaded.value = true
|
||||
} catch (e) {
|
||||
error.value = e instanceof Error ? e.message : String(e)
|
||||
} finally {
|
||||
@@ -101,8 +116,10 @@ export const useClipsStore = defineStore('clips', () => {
|
||||
total,
|
||||
loading,
|
||||
error,
|
||||
loaded,
|
||||
upsert,
|
||||
removeLocal,
|
||||
reset,
|
||||
load,
|
||||
loadMore,
|
||||
fetchOne,
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
|
||||
import { notifyUnauthorized } from '@/api/client'
|
||||
import type { Clip } from '@/api/types'
|
||||
import { useClipsStore } from '@/stores/clips'
|
||||
|
||||
export type SyncStatus = 'offline' | 'connecting' | 'live'
|
||||
|
||||
type ServerMessage =
|
||||
| { type: 'hello' }
|
||||
| { type: 'ping' }
|
||||
| { type: 'clip.created' | 'clip.updated'; data: Clip }
|
||||
| { type: 'clip.deleted'; data: { id: number } }
|
||||
|
||||
const MIN_RETRY_MS = 1_000
|
||||
const MAX_RETRY_MS = 30_000
|
||||
// Server pings every 30 s; silence beyond this means the connection is dead
|
||||
const WATCHDOG_MS = 75_000
|
||||
const CLOSE_UNAUTHORIZED = 4401
|
||||
|
||||
/**
|
||||
* Live sync: receives change events over a WebSocket and applies them to the clip store.
|
||||
* Writes always go through the REST API; the socket is read-only.
|
||||
*/
|
||||
export const useSyncStore = defineStore('sync', () => {
|
||||
const status = ref<SyncStatus>('offline')
|
||||
|
||||
let socket: WebSocket | null = null
|
||||
let wanted = false
|
||||
let retryDelay = MIN_RETRY_MS
|
||||
let retryTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let watchdogTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let listenersAdded = false
|
||||
|
||||
function handle(message: ServerMessage): void {
|
||||
const clips = useClipsStore()
|
||||
switch (message.type) {
|
||||
case 'hello':
|
||||
status.value = 'live'
|
||||
retryDelay = MIN_RETRY_MS
|
||||
// Events may have been missed while disconnected
|
||||
if (clips.loaded) void clips.load()
|
||||
break
|
||||
case 'clip.created':
|
||||
case 'clip.updated':
|
||||
clips.upsert(message.data)
|
||||
break
|
||||
case 'clip.deleted':
|
||||
clips.removeLocal(message.data.id)
|
||||
break
|
||||
case 'ping':
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
function resetWatchdog(ws: WebSocket): void {
|
||||
clearTimeout(watchdogTimer)
|
||||
watchdogTimer = setTimeout(() => drop(ws), WATCHDOG_MS)
|
||||
}
|
||||
|
||||
/** Abandon a (possibly half-dead) socket and reconnect. */
|
||||
function drop(ws: WebSocket): void {
|
||||
if (socket !== ws) return
|
||||
ws.onclose = ws.onmessage = ws.onerror = null
|
||||
ws.close()
|
||||
socket = null
|
||||
scheduleReconnect()
|
||||
}
|
||||
|
||||
function connect(): void {
|
||||
if (!wanted || socket) return
|
||||
clearTimeout(retryTimer)
|
||||
status.value = 'connecting'
|
||||
|
||||
const scheme = location.protocol === 'https:' ? 'wss' : 'ws'
|
||||
const ws = new WebSocket(`${scheme}://${location.host}/api/ws`)
|
||||
socket = ws
|
||||
resetWatchdog(ws)
|
||||
|
||||
ws.onmessage = (event: MessageEvent<string>) => {
|
||||
resetWatchdog(ws)
|
||||
try {
|
||||
handle(JSON.parse(event.data) as ServerMessage)
|
||||
} catch (e) {
|
||||
console.warn('Ignoring invalid sync message', e)
|
||||
}
|
||||
}
|
||||
ws.onclose = (event: CloseEvent) => {
|
||||
if (socket !== ws) return
|
||||
socket = null
|
||||
clearTimeout(watchdogTimer)
|
||||
if (event.code === CLOSE_UNAUTHORIZED) {
|
||||
stop()
|
||||
notifyUnauthorized()
|
||||
return
|
||||
}
|
||||
scheduleReconnect()
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleReconnect(): void {
|
||||
clearTimeout(watchdogTimer)
|
||||
status.value = wanted ? 'connecting' : 'offline'
|
||||
if (!wanted) return
|
||||
const jitter = 0.5 + Math.random()
|
||||
retryTimer = setTimeout(connect, retryDelay * jitter)
|
||||
retryDelay = Math.min(retryDelay * 2, MAX_RETRY_MS)
|
||||
}
|
||||
|
||||
/** Reconnect right away, e.g. when an iPhone brings the app back to the foreground. */
|
||||
function reconnectNow(): void {
|
||||
if (!wanted || document.visibilityState !== 'visible') return
|
||||
if (socket && socket.readyState === WebSocket.OPEN) return
|
||||
if (socket) drop(socket)
|
||||
clearTimeout(retryTimer)
|
||||
retryDelay = MIN_RETRY_MS
|
||||
connect()
|
||||
}
|
||||
|
||||
function start(): void {
|
||||
wanted = true
|
||||
if (!listenersAdded) {
|
||||
document.addEventListener('visibilitychange', reconnectNow)
|
||||
window.addEventListener('online', reconnectNow)
|
||||
listenersAdded = true
|
||||
}
|
||||
connect()
|
||||
}
|
||||
|
||||
function stop(): void {
|
||||
wanted = false
|
||||
clearTimeout(retryTimer)
|
||||
clearTimeout(watchdogTimer)
|
||||
if (socket) {
|
||||
socket.onclose = socket.onmessage = socket.onerror = null
|
||||
socket.close(1000)
|
||||
socket = null
|
||||
}
|
||||
status.value = 'offline'
|
||||
}
|
||||
|
||||
return { status, start, stop }
|
||||
})
|
||||
Reference in new issue
Block a user