Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/hyperion-autologging/src/ALSurfaceHierarchy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ export abstract class ALSurfaceHierarchyNode<
}

removeChild(child: Child): boolean {
if (this.children.get(child.surfaceName) !== child) {
return false;
}
return this.children.delete(child.surfaceName);
}

Expand Down
6 changes: 4 additions & 2 deletions packages/hyperion-autologging/test/ALSurfaceHierarchy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class TestSurfaceNode extends ALSurfaceHierarchyNode<TestSurfaceNode> {
}

describe('ALSurfaceHierarchyNode', () => {
test('uses name-keyed Map replacement and removal semantics', () => {
test('does not remove a replacement through a stale child instance', () => {
const root = new TestSurfaceNode('root', null, null);
const first = new TestSurfaceNode('child', '/first', root);
const second = new TestSurfaceNode('child', '/second', root);
Expand All @@ -29,7 +29,9 @@ describe('ALSurfaceHierarchyNode', () => {

expect(root.getChild('child')).toBe(second);
expect(root.getChildren()).toEqual([second]);
expect(root.removeChild(first)).toBe(true);
expect(root.removeChild(first)).toBe(false);
expect(root.getChild('child')).toBe(second);
expect(root.removeChild(second)).toBe(true);
expect(root.getChild('child')).toBeNull();
});

Expand Down
7 changes: 7 additions & 0 deletions packages/hyperion-react-native/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,13 @@ portable hierarchy contracts live in `hyperion-autologging`; mobile nodes have
no DOM element and return a shared frozen empty collection from `getElements()`.
App lifecycle is injected structurally through `reactNativeAppLifecycle({
AppState })`, so the portable runtime has no eager `react-native` dependency.
Set `transientInactiveMs` to a positive duration to suppress non-active
transitions that return to active before that duration elapses. It defaults to
zero, which dispatches every transition immediately.

`AutoLogging.init()` accepts a positive, finite `sessionTimeoutMs` for mobile
in-memory session rotation. The default remains 30 minutes; invalid values use
that default.

## Compatibility setup

Expand Down
104 changes: 91 additions & 13 deletions packages/hyperion-react-native/src/ALAppLifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,30 @@ export type { ALAppStateListener } from './IReactNative';

export const REACT_NATIVE_APP_LIFECYCLE_PLUGIN = 'react-native-app-lifecycle';

interface PendingAppStateTransition {
state: AppStateStatus;
readonly previousState: AppStateStatus;
readonly timestamp: number;
readonly timer: ReturnType<typeof setTimeout>;
}

export class ALAppLifecycle implements ALAppLifecycleEnvironment {
private currentState: AppStateStatus | null = null;
private readonly listeners = new Set<ALAppStateListener>();
private pendingTransition: PendingAppStateTransition | null = null;
private subscription: { remove(): void } | null = null;
private readonly transientInactiveMs: number;

constructor(
private readonly appState: ReactNativeAppState,
private readonly now: () => number
) {}
private readonly now: () => number,
transientInactiveMs = 0
) {
this.transientInactiveMs =
Number.isFinite(transientInactiveMs) && transientInactiveMs > 0
? transientInactiveMs
: 0;
}

getCurrentState(): AppStateStatus | null {
return this.currentState;
Expand All @@ -40,32 +55,91 @@ export class ALAppLifecycle implements ALAppLifecycleEnvironment {
if (this.subscription != null) return;
this.currentState = this.appState.currentState;
this.subscription = this.appState.addEventListener('change', (state) => {
const previousState = this.currentState;
this.currentState = state;
const timestamp = this.now();
const listenerCount = this.listeners.size;
let visited = 0;
for (const listener of this.listeners) {
if (visited++ >= listenerCount) break;
try {
listener(state, previousState, timestamp);
} catch {
// One lifecycle capability must not block the others or AppState.
const pendingTransition = this.pendingTransition;
if (pendingTransition != null) {
if (state === 'active') {
this.clearPendingTransition();
if (
timestamp - pendingTransition.timestamp >=
this.transientInactiveMs
) {
this.dispatch(
pendingTransition.state,
pendingTransition.previousState,
pendingTransition.timestamp
);
if (this.subscription != null) {
this.dispatch(state, pendingTransition.state, timestamp);
}
}
} else {
pendingTransition.state = state;
}
return;
}
if (
this.transientInactiveMs > 0 &&
this.currentState === 'active' &&
state !== 'active'
) {
const transition: PendingAppStateTransition = {
state,
previousState: this.currentState,
timestamp,
timer: setTimeout(() => {
if (this.pendingTransition !== transition) return;
this.pendingTransition = null;
this.dispatch(
transition.state,
transition.previousState,
transition.timestamp
);
}, this.transientInactiveMs),
};
this.pendingTransition = transition;
return;
}
this.dispatch(state, this.currentState, timestamp);
});
}

dispose(): void {
this.clearPendingTransition();
this.subscription?.remove();
this.subscription = null;
this.currentState = null;
this.listeners.clear();
}

private clearPendingTransition(): void {
if (this.pendingTransition == null) return;
clearTimeout(this.pendingTransition.timer);
this.pendingTransition = null;
}

private dispatch(
state: AppStateStatus,
previousState: AppStateStatus | null,
timestamp: number
): void {
this.currentState = state;
const listenerCount = this.listeners.size;
let visited = 0;
for (const listener of this.listeners) {
if (visited++ >= listenerCount) break;
try {
listener(state, previousState, timestamp);
} catch {
// One lifecycle capability must not block the others or AppState.
}
}
}
}

export interface ReactNativeAppLifecycleOptions {
readonly AppState: ReactNativeAppState;
readonly transientInactiveMs?: number;
}

export function reactNativeAppLifecycle<
Expand All @@ -78,7 +152,11 @@ export function reactNativeAppLifecycle<
if (appState == null) {
throw new Error('React Native app lifecycle requires AppState.');
}
const lifecycle = new ALAppLifecycle(appState, context.now);
const lifecycle = new ALAppLifecycle(
appState,
context.now,
options.transientInactiveMs
);
context.installAppLifecycle(lifecycle);
return {
start() {
Expand Down
1 change: 1 addition & 0 deletions packages/hyperion-react-native/src/ALCompatibility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ export interface CompatibilityInitOptions
readonly props?: LegacyComponentPropsOptions | null;
readonly componentProps?: LegacyComponentPropsOptions | null;
readonly features?: ALFeatureConfig;
readonly sessionTimeoutMs?: number;
}

export function createReactNativePlugins(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -341,12 +341,12 @@ function invokeRootInstrumentedHandler(
}
return handler.apply(receiver, args);
}
recordActivityWithoutAffectingHandler(state);
try {
emitUIEvent(state, snapshot, eventType, propName, eventValue);
} catch {
// Logging failures must not affect the application handler.
}
recordActivityWithoutAffectingHandler(state);
return handler.apply(receiver, args);
}

Expand Down
7 changes: 2 additions & 5 deletions packages/hyperion-react-native/src/ALPluginAutoLogging.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,7 @@

import type { BaseChannelEventType } from 'hyperion-channel/src/Channel';
import type { AutoLoggingChannel } from 'hyperion-autologging/src/ALChannel';
import {
clearActiveRuntimeContext,
setActiveRuntimeContext,
} from './ALActiveRuntime';
import { clearActiveRuntimeContext } from './ALActiveRuntime';
import {
createReactNativeRuntime,
type ALReactNativePlugin,
Expand All @@ -23,6 +20,7 @@ export interface PluginInitOptions<
> {
readonly channel: AutoLoggingChannel<EventMap>;
readonly plugins: readonly ALReactNativePlugin<EventMap>[];
readonly sessionTimeoutMs?: number;
}

type InitializationState =
Expand All @@ -47,7 +45,6 @@ export function init<
options as unknown as ALReactNativeRuntimeOptions<BaseChannelEventType>
);
activeRuntime = runtime;
setActiveRuntimeContext(runtime.context);
initializationState = 'initialized';
return true;
} catch (error) {
Expand Down
35 changes: 23 additions & 12 deletions packages/hyperion-react-native/src/ALRuntime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ import type {
import { createALEventFactory } from 'hyperion-autologging/src/ALEventFactory';
import type { ALManagedPlugin } from 'hyperion-autologging/src/ALPlugin';
import { ALPluginRuntime } from 'hyperion-autologging/src/ALPluginRuntime';
import {
clearActiveRuntimeContext,
setActiveRuntimeContext,
} from './ALActiveRuntime';
import type { ALAppLifecycleEnvironment } from './IReactNative';
import { ALReactNativeSession } from './ALSession';
import type { ALLoggableEvent, SurfaceMetadataValue } from './ALTypes';
Expand All @@ -35,6 +39,7 @@ export interface ALReactNativeRuntimeOptions<
readonly channel: AutoLoggingChannel<EventMap>;
readonly plugins: readonly ALReactNativePlugin<EventMap>[];
readonly now?: () => number;
readonly sessionTimeoutMs?: number;
}

export interface ALReactNativeRuntime<EventMap extends BaseChannelEventType> {
Expand All @@ -44,20 +49,16 @@ export interface ALReactNativeRuntime<EventMap extends BaseChannelEventType> {
dispose(): boolean;
}

function createRuntimeContext(now: () => number): ALReactNativeRuntimeContext {
const session = new ALReactNativeSession(now);
const factory = createALEventFactory<SurfaceMetadataValue>({
function createRuntimeContext(
now: () => number,
sessionTimeoutMs?: number
): ALReactNativeRuntimeContext {
const session = new ALReactNativeSession(now, sessionTimeoutMs);
const eventFactory = createALEventFactory<SurfaceMetadataValue>({
now,
nextEventIndex: () => session.nextEventIndex(),
getBaseMetadata: () => ({}),
});
const eventFactory: ALEventFactory<SurfaceMetadataValue> = {
createEvent(options?: ALCreateEventOptions<SurfaceMetadataValue>) {
const eventTimestamp = options?.eventTimestamp ?? now();
session.getSessionId(eventTimestamp);
return factory.createEvent({ ...options, eventTimestamp });
},
};
let appLifecycle: ALAppLifecycleEnvironment | null = null;
return {
eventFactory,
Expand All @@ -79,9 +80,19 @@ function createRuntimeContext(now: () => number): ALReactNativeRuntimeContext {
export function createReactNativeRuntime<EventMap extends BaseChannelEventType>(
options: ALReactNativeRuntimeOptions<EventMap>
): ALReactNativeRuntime<EventMap> {
const context = createRuntimeContext(options.now ?? Date.now);
const context = createRuntimeContext(
options.now ?? Date.now,
options.sessionTimeoutMs
);
const runtime = new ALPluginRuntime(options.channel, context);
runtime.initialize(options.plugins);
// Startup events may have subscribers that read the active session context.
setActiveRuntimeContext(context);
try {
runtime.initialize(options.plugins);
} catch (error) {
clearActiveRuntimeContext(context);
throw error;
}
return {
channel: options.channel,
context,
Expand Down
3 changes: 1 addition & 2 deletions packages/hyperion-react-native/src/ALScreen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,8 @@ export function setCurrentScreen(
const previousScreen = runtime.currentScreen;
const screenId = context.session.rotateScreenId();
runtime.currentScreen = { name: explicitName, screenId };
context.session.recordActivity();
if (!runtime.publishTransitions) {
context.session.recordActivity();
return true;
}
const event = {
Expand All @@ -101,7 +101,6 @@ export function setCurrentScreen(
'al_screen_transition_event',
event as ALScreenTransitionEventData
);
context.session.recordActivity();
return true;
}

Expand Down
17 changes: 10 additions & 7 deletions packages/hyperion-react-native/src/ALSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,20 +25,20 @@ export class ALReactNativeSession {
private screenId = generateId();
private lastActivityTime: number;
private eventIndex = 0;
private readonly sessionTimeoutMs: number;

constructor(
private readonly now: () => number = Date.now,
private readonly sessionTimeoutMs = DEFAULT_SESSION_TIMEOUT_MS
sessionTimeoutMs = DEFAULT_SESSION_TIMEOUT_MS
) {
this.sessionTimeoutMs =
Number.isFinite(sessionTimeoutMs) && sessionTimeoutMs > 0
? sessionTimeoutMs
: DEFAULT_SESSION_TIMEOUT_MS;
this.lastActivityTime = now();
}

getSessionId(timestamp = this.now()): string {
if (timestamp - this.lastActivityTime > this.sessionTimeoutMs) {
this.sessionId = generateId();
this.eventIndex = 0;
this.lastActivityTime = timestamp;
}
getSessionId(): string {
return this.sessionId;
}

Expand All @@ -56,6 +56,9 @@ export class ALReactNativeSession {
}

recordActivity(timestamp = this.now()): void {
if (timestamp - this.lastActivityTime > this.sessionTimeoutMs) {
this.sessionId = generateId();
}
this.lastActivityTime = timestamp;
}

Expand Down
1 change: 1 addition & 0 deletions packages/hyperion-react-native/src/AutoLogging.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export function init<
return initPlugins({
channel: options.channel as AutoLoggingChannel<ALReactNativeEventMap>,
plugins: createReactNativePlugins(options),
sessionTimeoutMs: options.sessionTimeoutMs,
});
}

Expand Down
Loading
Loading