import { acquireInterruptLockResponse, releaseInterruptLockResponse, renewInterruptLockResponse, } from '../schemas'; import { IdleCallback, InterruptLock, MessageBroker, Runtime, RuntimeListener, RuntimeWindow, } from '../types'; import { generateRequestId } from '../utils'; interface AcquireLockPromise { resolve: (lock: InterruptLock) => void; reject: (error: Error) => void; } interface RenewLockPromise { resolve: () => void; reject: (error: Error) => void; } interface ReleaseLockPromise { resolve: () => void; reject: (error: Error) => void; } export const interactionEvents = [ 'mousemove', 'mousedown', 'keydown', 'touchstart', 'click', ]; // The Runtime API allows apps to interact with the playlist runtime. export function initializeRuntime( messageBroker: MessageBroker, window: RuntimeWindow ): Runtime { let didSendReady = false; const runtimeListeners: Record> = {}; const acquireLockRequests: Record = {}; const renewLockRequests: Record = {}; const releaseLockRequests: Record = {}; const interruptLocks: Record = {}; // Default idle settings. const defaultIdleContainer = typeof window !== 'undefined' ? window.document : null; const defaultIdleSeconds = 30; // Register listener to receive incoming messages. messageBroker.registerListener((type, payload) => { if (type === 'play') { // Notify play listeners. const listeners = runtimeListeners['play']; if (listeners) { for (const listener of listeners) { listener(); } } } else if (type === 'runtime-acquire-interrupt-lock-response') { const parsed = acquireInterruptLockResponse.safeParse(payload); if (parsed.success) { const { requestId, lock, error } = parsed.data; // Find the promise for the charge request and resolve it or reject it // if the charge response contained an error. const acquireLockPromise = acquireLockRequests[requestId]; if (acquireLockPromise) { if (lock) { interruptLocks[lock.id] = createInterruptLock( lock.id, lock.expiresAt ); acquireLockPromise.resolve(interruptLocks[lock.id]); } else if (error) { acquireLockPromise.reject(new Error(error.message)); } delete acquireLockPromise[requestId]; } else { console.warn( 'Received runtime-interrupt-lock-response for unknown request', requestId ); } } else { console.warn( 'Invalid runtime-interrupt-lock-response payload received', parsed.error ); } } else if (type === 'runtime-renew-interrupt-lock-response') { const parsed = renewInterruptLockResponse.safeParse(payload); if (parsed.success) { const { requestId, lock, error } = parsed.data; if (lock) { const interruptLock = interruptLocks[lock.id]; const renewLockPromise = renewLockRequests[requestId]; if (interruptLock && renewLockPromise) { interruptLock.expiresAt = lock.expiresAt; renewLockPromise.resolve(); delete renewLockRequests[lock.id]; } else { console.warn( 'Received runtime-interrupt-lock-renew-response for unknown lock', requestId, lock.id ); } } else if (error) { console.warn( 'Received runtime-interrupt-lock-renew-response error', error.message ); } } else { console.warn( 'Invalid runtime-interrupt-lock-renew-response payload received', parsed.error ); } } else if (type === 'runtime-release-interrupt-lock-response') { const parsed = releaseInterruptLockResponse.safeParse(payload); if (parsed.success) { const { requestId, lock, error } = parsed.data; if (lock) { const interruptLock = interruptLocks[lock.id]; const releaseLockPromise = releaseLockRequests[requestId]; if (interruptLock && releaseLockPromise) { delete interruptLocks[lock.id]; releaseLockPromise.resolve(); delete renewLockRequests[lock.id]; } else { console.warn( 'Received runtime-interrupt-lock-release-response for unknown lock', requestId, lock.id ); } } else if (error) { console.warn( 'Received runtime-interrupt-lock-release-response error', error.message ); } } else { console.warn( 'Invalid runtime-interrupt-lock-release-response payload received', parsed.error ); } } }); const createInterruptLock = ( lockId: string, expiresAt: number ): InterruptLock => { const lock = { id: lockId, expiresAt, async renew() { const requestId = generateRequestId(); messageBroker.sendMessage('runtime-renew-interrupt-lock-request', { requestId, lockId, }); const renewLockPromise = new Promise((resolve, reject) => { renewLockRequests[requestId] = { resolve, reject }; }); return renewLockPromise; }, async release() { const requestId = generateRequestId(); messageBroker.sendMessage('runtime-release-interrupt-lock-request', { requestId, lockId, }); const releaseLockPromise = new Promise((resolve, reject) => { releaseLockRequests[requestId] = { resolve, reject }; }); return releaseLockPromise; }, }; return lock; }; const runtime: Runtime = { ready() { // Only send ready once. if (didSendReady) return; messageBroker.sendMessage('ready'); didSendReady = true; }, complete(error) { // Unwrap error message. let errorMessage: string | null; if (error instanceof Error) { errorMessage = error.message; } else if (typeof error === 'string') { errorMessage = error; } else { errorMessage = null; } if (errorMessage) { messageBroker.sendMessage('complete', errorMessage); } else { messageBroker.sendMessage('complete'); } }, subscribe(eventName, listener) { if (!runtimeListeners[eventName]) { runtimeListeners[eventName] = new Set(); // Only send subscribe message for first runtime event listener. // This event instructs the runtime to send runtime events. messageBroker.sendMessage('runtime-subscribe', eventName); } runtimeListeners[eventName].add(listener); return () => { runtimeListeners[eventName].delete(listener); // Send unsubscribe message when there are no more listeners for worker. // This event instructs the runtime to stop sending worker state for the worker name. if (runtimeListeners[eventName].size === 0) { messageBroker.sendMessage('runtime-unsubscribe', eventName); delete runtimeListeners[eventName]; } }; }, async acquireInterruptLock() { // Generate a unique id for the acquire lock request. const requestId = generateRequestId(); messageBroker.sendMessage('runtime-acquire-interrupt-lock-request', { requestId, }); const acquireLockPromise = new Promise( (resolve, reject) => { acquireLockRequests[requestId] = { resolve, reject }; } ); return acquireLockPromise; }, addIdleListener(...args) { let container: HTMLElement | Document | null = defaultIdleContainer; let secondsUntilIdle = defaultIdleSeconds; let callback: IdleCallback | null = null; if (typeof args[0] === 'number') { // If the first argument is a number then it is the secondsUntilIdle. // ie. runtime.addIdleListener(5) secondsUntilIdle = args[0]; } else if ( args[0] instanceof window.HTMLElement || args[0] instanceof window.Document ) { // If the first argument is an HTMLElement or Document then it is the container. // ie. runtime.addIdleListener(container) container = args[0]; } if (typeof args[1] === 'number') { // If the second argument is a number then it is the secondsUntilIdle. // ie. runtime.addIdleListener(container, 5) secondsUntilIdle = args[1]; } if (typeof args[args.length - 1] === 'function') { // If the last argument is a function then it is the idle callback. // ie. runtime.addIdleListener((isIdle) => { ... }) // ie. runtime.addIdleListener(5, (isIdle) => { ... }) // ie. runtime.addIdleListener(container, 5, (isIdle) => { ... }) callback = args[args.length - 1]; } let lock: InterruptLock | null = null; let idleTimeout: ReturnType | null = null; let throttleTimeout: ReturnType | null = null; let renewTimeout: ReturnType | null = null; const queueRenewLock = async () => { if (!lock) return; // Clear existing renew timeout. if (renewTimeout) { clearTimeout(renewTimeout); } // Renew the lock 2 seconds before it expires. const renewAt = lock.expiresAt - 2000; const renewIn = Math.max(renewAt - Date.now(), 0); renewTimeout = setTimeout(async () => { if (!lock) return; try { await lock.renew(); queueRenewLock(); } catch (err) { console.warn('Raydiant SDK: Failed to renew lock', err); } renewTimeout = null; }, renewIn); }; const handleInteraction = async () => { // Throttle interactions by 1 second to prevent requesting/renewing locks too frequently. if (throttleTimeout) return; throttleTimeout = setTimeout(() => { throttleTimeout = null; }, 1000); // Clear existing idle timeout. if (idleTimeout) { clearTimeout(idleTimeout); } // Acquire new lock is one does not exist. if (!lock) { try { lock = await runtime.acquireInterruptLock(); queueRenewLock(); } catch (err) { console.warn('Raydiant SDK: Failed to acquire lock', err); } // If there is no lock then this is the first interaction since the last idle, // call the idle callback with isIdle=false. if (callback) { callback(false); } } // Start the idle timeout. Release the lock and call the idle callback when // the timeout expires. idleTimeout = setTimeout(async () => { // Clear the renew timeout. if (renewTimeout) { clearTimeout(renewTimeout); } // Release the lock. if (lock) { try { await lock.release(); } catch (err) { console.warn('Raydiant SDK: Failed to release lock', err); } lock = null; } // If the idle timeout expires then call the idle callback with isIdle=true. if (callback) { callback(true); } }, secondsUntilIdle * 1000); }; if (container) { for (const event of interactionEvents) { container.addEventListener(event, handleInteraction); } } // Start the idle timeout to set initial state. The first interaction will clear this timeout // and request a lock. idleTimeout = setTimeout(() => { if (callback) { callback(true); } }, secondsUntilIdle * 1000); // Return the remove idle listener function. return async () => { if (container) { for (const event of interactionEvents) { container.removeEventListener(event, handleInteraction); } } if (idleTimeout) { clearTimeout(idleTimeout); } if (throttleTimeout) { clearTimeout(throttleTimeout); } if (renewTimeout) { clearTimeout(renewTimeout); } if (lock) { await lock.release(); lock = null; } }; }, }; return runtime; }