create-expo-updates-server 0.1.5 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/dist/template/.dockerignore +16 -0
  2. package/dist/template/README.md +51 -660
  3. package/dist/template/app/api/admin/device-targets/route.test.ts +43 -0
  4. package/dist/template/app/api/admin/device-targets/route.ts +91 -0
  5. package/dist/template/app/api/admin/devices/route.test.ts +41 -0
  6. package/dist/template/app/api/admin/devices/route.ts +15 -0
  7. package/dist/template/app/api/admin/updates/[encodedKey]/audience/route.ts +75 -0
  8. package/dist/template/app/api/device-heartbeat/route.ts +2 -0
  9. package/dist/template/app/globals.css +114 -15
  10. package/dist/template/app/layout.tsx +12 -4
  11. package/dist/template/app/login/page.tsx +22 -18
  12. package/dist/template/app/updates/[encodedKey]/page.tsx +112 -88
  13. package/dist/template/app/updates/devices/page.tsx +264 -0
  14. package/dist/template/app/updates/embedded/page.tsx +102 -68
  15. package/dist/template/app/updates/emergency-redirects/page.tsx +144 -111
  16. package/dist/template/app/updates/layout.tsx +6 -1
  17. package/dist/template/app/updates/page.tsx +262 -212
  18. package/dist/template/components/admin/admin-shell.tsx +196 -0
  19. package/dist/template/components/admin/language-switcher.tsx +25 -0
  20. package/dist/template/components/admin/theme-provider.tsx +15 -0
  21. package/dist/template/components/ui/alert.tsx +65 -0
  22. package/dist/template/components/ui/badge.tsx +47 -0
  23. package/dist/template/components/ui/button.tsx +63 -0
  24. package/dist/template/components/ui/card.tsx +91 -0
  25. package/dist/template/components/ui/chart.tsx +373 -0
  26. package/dist/template/components/ui/checkbox.tsx +31 -0
  27. package/dist/template/components/ui/dialog.tsx +158 -0
  28. package/dist/template/components/ui/dropdown-menu.tsx +256 -0
  29. package/dist/template/components/ui/input.tsx +20 -0
  30. package/dist/template/components/ui/label.tsx +23 -0
  31. package/dist/template/components/ui/native-select.tsx +61 -0
  32. package/dist/template/components/ui/popover.tsx +88 -0
  33. package/dist/template/components/ui/scroll-area.tsx +57 -0
  34. package/dist/template/components/ui/select.tsx +189 -0
  35. package/dist/template/components/ui/separator.tsx +27 -0
  36. package/dist/template/components/ui/sheet.tsx +142 -0
  37. package/dist/template/components/ui/sidebar.tsx +736 -0
  38. package/dist/template/components/ui/skeleton.tsx +13 -0
  39. package/dist/template/components/ui/switch.tsx +34 -0
  40. package/dist/template/components/ui/table.tsx +115 -0
  41. package/dist/template/components/ui/tabs.tsx +90 -0
  42. package/dist/template/components/ui/textarea.tsx +17 -0
  43. package/dist/template/components/ui/tooltip.tsx +56 -0
  44. package/dist/template/components.json +22 -0
  45. package/dist/template/docs/admin-ui.md +35 -0
  46. package/dist/template/docs/device-targeting.md +129 -0
  47. package/dist/template/docs/doctor.md +137 -0
  48. package/dist/template/docs/expo-app-setup.md +174 -47
  49. package/dist/template/docs/getting-started.md +105 -146
  50. package/dist/template/docs/getting-started.ru.md +106 -191
  51. package/dist/template/docs/index.md +14 -33
  52. package/dist/template/docs/installation-telemetry.md +233 -0
  53. package/dist/template/docs/migrations/2026-10-16-manifest-identity.sql +89 -0
  54. package/dist/template/docs/migrations/2026-10-19-device-heartbeat.sql +131 -0
  55. package/dist/template/docs/migrations/2026-10-22-device-analytics.sql +264 -0
  56. package/dist/template/docs/migrations/2026-10-22-device-targeting-activation.sql +108 -0
  57. package/dist/template/docs/migrations/2026-10-22-device-targeting.sql +130 -0
  58. package/dist/template/docs/migrations/2026-10-22-device-version-metadata.sql +154 -0
  59. package/dist/template/docs/migrations/schema.sql +868 -6
  60. package/dist/template/docs/npm-installer.md +15 -30
  61. package/dist/template/docs/operations-guide.md +87 -0
  62. package/dist/template/docs/ota-client-lifecycle.md +263 -0
  63. package/dist/template/docs/ota-update-policy.md +36 -2
  64. package/dist/template/docs/supabase-setup.md +4 -0
  65. package/dist/template/hooks/use-mobile.ts +21 -0
  66. package/dist/template/lib/utils.ts +6 -0
  67. package/dist/template/package-lock.json +2325 -101
  68. package/dist/template/package.json +13 -3
  69. package/dist/template/scripts/configure-expo-app.mjs +11 -15
  70. package/dist/template/scripts/doctor.mjs +51 -0
  71. package/dist/template/scripts/ensure-test-bucket.mjs +21 -0
  72. package/dist/template/scripts/lib/device-identity.test.ts +29 -0
  73. package/dist/template/scripts/lib/doctor-probes.mjs +139 -0
  74. package/dist/template/scripts/lib/doctor.mjs +208 -0
  75. package/dist/template/scripts/lib/doctor.test.mjs +262 -0
  76. package/dist/template/scripts/lib/expo-app-configurator.mjs +14 -9
  77. package/dist/template/scripts/lib/expo-app-configurator.test.ts +3 -2
  78. package/dist/template/scripts/lib/ota-client-configurator.mjs +69 -0
  79. package/dist/template/scripts/lib/ota-client-configurator.test.ts +88 -0
  80. package/dist/template/scripts/lib/ota-client.test.ts +55 -0
  81. package/dist/template/scripts/lib/ota-root-hook-patcher.mjs +173 -0
  82. package/dist/template/scripts/lib/ota-root-hook-patcher.test.ts +123 -0
  83. package/dist/template/scripts/lib/ota-update-controller.test.ts +231 -0
  84. package/dist/template/scripts/tests/device-analytics-migrations.mjs +80 -0
  85. package/dist/template/scripts/tests/device-analytics.mjs +126 -0
  86. package/dist/template/scripts/tests/device-heartbeat.mjs +86 -0
  87. package/dist/template/scripts/tests/device-targeting-activation.mjs +111 -0
  88. package/dist/template/scripts/tests/device-targeting.mjs +39 -0
  89. package/dist/template/scripts/tests/device-version-metadata.mjs +31 -0
  90. package/dist/template/scripts/tests/manifest-identity-concurrency.mjs +106 -0
  91. package/dist/template/scripts/tests/manifest-identity.sql +204 -0
  92. package/dist/template/src/client/admin-types.ts +1 -0
  93. package/dist/template/src/client/devices/analytics.tsx +429 -0
  94. package/dist/template/src/client/devices/device-name.tsx +82 -0
  95. package/dist/template/src/client/devices/registry.tsx +399 -0
  96. package/dist/template/src/client/devices/use-devices-report.ts +108 -0
  97. package/dist/template/src/client/devices/version-adoption-chart.tsx +269 -0
  98. package/dist/template/src/client/devices/version-groups.test.ts +57 -0
  99. package/dist/template/src/client/devices/version-groups.ts +101 -0
  100. package/dist/template/src/client/distribution-control.tsx +135 -81
  101. package/dist/template/src/client/guard-action-combobox.tsx +13 -24
  102. package/dist/template/src/client/i18n/en.json +286 -0
  103. package/dist/template/src/client/i18n/messages.test.ts +42 -0
  104. package/dist/template/src/client/i18n/messages.ts +31 -0
  105. package/dist/template/src/client/i18n/provider.tsx +55 -0
  106. package/dist/template/src/client/i18n/use-formatters.ts +38 -0
  107. package/dist/template/src/client/logout-button.tsx +3 -1
  108. package/dist/template/src/client/update-audience-editor.tsx +285 -0
  109. package/dist/template/src/client/update-policy-editor.tsx +53 -41
  110. package/dist/template/src/server/controllers/manifest.test.ts +250 -7
  111. package/dist/template/src/server/controllers/manifest.ts +39 -31
  112. package/dist/template/src/server/devices/audience.test.ts +48 -0
  113. package/dist/template/src/server/devices/audience.ts +86 -0
  114. package/dist/template/src/server/devices/heartbeat.test.ts +39 -0
  115. package/dist/template/src/server/devices/heartbeat.ts +75 -0
  116. package/dist/template/src/server/devices/report-types.ts +114 -0
  117. package/dist/template/src/server/devices/report.test.ts +29 -0
  118. package/dist/template/src/server/devices/report.ts +27 -0
  119. package/dist/template/src/server/lib/admin-audience-activation.test.ts +94 -0
  120. package/dist/template/src/server/lib/admin-updates.ts +32 -168
  121. package/dist/template/src/server/lib/distribution-control.test.ts +23 -2
  122. package/dist/template/src/server/lib/distribution-control.ts +13 -4
  123. package/dist/template/src/server/lib/supabase.js +10 -10
  124. package/dist/template/src/server/lib/supabase.test.ts +11 -0
  125. package/dist/template/src/server/manifest/manifest-identity.test.ts +30 -0
  126. package/dist/template/src/server/manifest/manifest-identity.ts +24 -0
  127. package/dist/template/src/server/manifest/manifest-repository.ts +31 -102
  128. package/dist/template/src/server/manifest/manifest-response.ts +1 -1
  129. package/dist/template/templates/expo-app/ota-client/README.md +59 -0
  130. package/dist/template/templates/expo-app/ota-client/controller.js +60 -0
  131. package/dist/template/templates/expo-app/ota-client/device-identity.js +26 -0
  132. package/dist/template/templates/expo-app/ota-client/docs/update-lifecycle.md +52 -0
  133. package/dist/template/templates/expo-app/ota-client/index.d.ts +47 -0
  134. package/dist/template/templates/expo-app/ota-client/index.js +3 -0
  135. package/dist/template/templates/expo-app/ota-client/model/hooks/useOtaUpdates.js +48 -0
  136. package/dist/template/templates/expo-app/ota-client/model/update-controller.js +182 -0
  137. package/dist/template/templates/expo-app/ota-client/runtime.js +112 -0
  138. package/dist/template/templates/expo-app/ota-client/ui/ota-update-gate.js +56 -0
  139. package/dist/template-manifest.json +582 -77
  140. package/lib/cli.mjs +4 -6
  141. package/package.json +1 -1
@@ -75,9 +75,7 @@ alter table public.ota_updates
75
75
  create index if not exists idx_ota_updates_lookup
76
76
  on public.ota_updates (runtime_version, channel, platform, created_at desc);
77
77
 
78
- create unique index if not exists idx_ota_updates_one_active_per_scope
79
- on public.ota_updates (runtime_version, channel, platform)
80
- where is_active;
78
+ -- Multiple eligible releases are supported for device targeting and public fallback.
81
79
 
82
80
  comment on column public.ota_updates.disabled_at is
83
81
  'Inactive-state timestamp; disabled_at = created_at is the initial draft marker, not publication.';
@@ -180,11 +178,18 @@ begin
180
178
  if (
181
179
  old.latest_update_id is distinct from new.latest_update_id
182
180
  or old.active_update_id is distinct from new.active_update_id
181
+ or old.active_changed_at is distinct from new.active_changed_at
183
182
  ) then
184
183
  new.served_manifest_id := gen_random_uuid();
185
- new.served_manifest_changed_at := now();
184
+ -- Expo compares timestamps at millisecond precision, including within
185
+ -- one transaction. now() alone can produce equal publication times.
186
+ new.served_manifest_changed_at := greatest(
187
+ clock_timestamp(),
188
+ old.served_manifest_changed_at + interval '1 millisecond',
189
+ old.active_changed_at + interval '1 millisecond',
190
+ new.active_changed_at
191
+ );
186
192
  end if;
187
-
188
193
  return new;
189
194
  end;
190
195
  $$;
@@ -919,4 +924,861 @@ begin
919
924
  ) to service_role;
920
925
  end if;
921
926
  end;
922
- $$;
927
+ $$;
928
+
929
+ create or replace function public.ota_updates_rotate_channel_on_activation()
930
+ returns trigger
931
+ language plpgsql
932
+ as $$
933
+ begin
934
+ if not new.is_active then
935
+ return new;
936
+ end if;
937
+ if tg_op = 'UPDATE' then
938
+ if old.is_active then
939
+ return new;
940
+ end if;
941
+ end if;
942
+
943
+ -- latest_update_id may already point at this previously inactive draft.
944
+ -- Activating it must still advance the epoch and the manifest timestamp.
945
+ update public.ota_update_channels
946
+ set served_manifest_id = gen_random_uuid(),
947
+ served_manifest_changed_at = greatest(
948
+ clock_timestamp(),
949
+ served_manifest_changed_at + interval '1 millisecond',
950
+ active_changed_at + interval '1 millisecond'
951
+ )
952
+ where runtime_version = new.runtime_version
953
+ and channel = new.channel
954
+ and platform = new.platform;
955
+ return new;
956
+ end;
957
+ $$;
958
+
959
+ drop trigger if exists trg_ota_updates_rotate_channel_on_activation
960
+ on public.ota_updates;
961
+ create trigger trg_ota_updates_rotate_channel_on_activation
962
+ after insert or update of is_active on public.ota_updates
963
+ for each row execute function public.ota_updates_rotate_channel_on_activation();
964
+
965
+ create or replace function public.ota_served_manifest_preserve_identity()
966
+ returns trigger
967
+ language plpgsql
968
+ as $$
969
+ begin
970
+ if old.served_manifest_id is distinct from new.served_manifest_id
971
+ or old.update_id is distinct from new.update_id
972
+ or old.runtime_version is distinct from new.runtime_version
973
+ or old.channel is distinct from new.channel
974
+ or old.platform is distinct from new.platform then
975
+ raise exception 'OTA_MANIFEST_IDENTITY_CONFLICT: served manifest identity cannot be reassigned'
976
+ using errcode = '23514';
977
+ end if;
978
+ -- Repeated manifest checks must not change the first-recorded timestamp.
979
+ new.created_at := old.created_at;
980
+ return new;
981
+ end;
982
+ $$;
983
+
984
+ drop trigger if exists trg_ota_served_manifest_preserve_identity
985
+ on public.ota_served_manifest_log;
986
+ create trigger trg_ota_served_manifest_preserve_identity
987
+ before update on public.ota_served_manifest_log
988
+ for each row execute function public.ota_served_manifest_preserve_identity();
989
+
990
+ -- Installation telemetry (2026-10-19).
991
+ -- Apply after schema.sql (including manifest identity). Safe to reapply.
992
+ begin;
993
+ alter table public.ota_device_state
994
+ add column if not exists reported_update_id uuid,
995
+ add column if not exists resolved_update_id uuid,
996
+ add column if not exists update_label text,
997
+ add column if not exists launch_kind text not null default 'unknown' check (launch_kind in ('embedded','ota','unknown')),
998
+ add column if not exists native_version text,
999
+ add column if not exists native_build text,
1000
+ add column if not exists emergency_launch boolean not null default false,
1001
+ add column if not exists observed_at timestamptz,
1002
+ add column if not exists last_event_id uuid,
1003
+ add column if not exists last_sequence bigint not null default 0 check (last_sequence between 0 and 9007199254740991);
1004
+ alter table public.ota_device_transitions
1005
+ add column if not exists event_id uuid,
1006
+ add column if not exists before_state jsonb,
1007
+ add column if not exists after_state jsonb;
1008
+ create index if not exists idx_ota_device_state_seen on public.ota_device_state(last_seen_at desc, installation_id, platform);
1009
+
1010
+ -- Invoker privileges only; the application backend is the sole database caller.
1011
+ create or replace function public.ota_record_heartbeat(p_event jsonb)
1012
+ returns table(result text) language plpgsql set search_path = public as $$
1013
+ declare
1014
+ previous public.ota_device_state%rowtype;
1015
+ artifact uuid;
1016
+ label text;
1017
+ kind text;
1018
+ before_version jsonb;
1019
+ after_version jsonb;
1020
+ seq bigint := (p_event->>'sequence')::bigint;
1021
+ reported uuid := (p_event->>'updateId')::uuid;
1022
+ receipt timestamptz;
1023
+ begin
1024
+ if seq < 1 or seq > 9007199254740991 then raise exception 'INVALID_SEQUENCE'; end if;
1025
+ insert into public.ota_device_state(installation_id,platform,runtime_version,channel)
1026
+ values(p_event->>'installationId',p_event->>'platform',p_event->>'runtimeVersion',p_event->>'channel')
1027
+ on conflict (installation_id,platform) do nothing;
1028
+ select * into strict previous from public.ota_device_state
1029
+ where installation_id=p_event->>'installationId' and platform=p_event->>'platform' for update;
1030
+ if seq < previous.last_sequence then return query select 'stale'::text; return; end if;
1031
+ if seq = previous.last_sequence then
1032
+ if previous.last_event_id = (p_event->>'eventId')::uuid then
1033
+ return query select 'duplicate'::text; return;
1034
+ end if;
1035
+ raise exception 'HEARTBEAT_SEQUENCE_CONFLICT';
1036
+ end if;
1037
+ receipt := greatest(previous.last_seen_at, clock_timestamp());
1038
+ kind := case when (p_event->>'isEmbeddedLaunch')::boolean then 'embedded' else 'unknown' end;
1039
+ if kind <> 'embedded' and reported is not null then
1040
+ select u.update_id,u.comment into artifact,label from public.ota_updates u
1041
+ where u.runtime_version=p_event->>'runtimeVersion' and u.channel=p_event->>'channel' and u.platform=p_event->>'platform'
1042
+ and (u.update_id=reported or exists(select 1 from public.ota_served_manifest_log m
1043
+ where m.served_manifest_id=reported and m.update_id=u.update_id and m.runtime_version=u.runtime_version
1044
+ and m.channel=u.channel and m.platform=u.platform))
1045
+ order by (u.update_id=reported) asc limit 1;
1046
+ if artifact is null and previous.launch_kind='ota' and previous.reported_update_id=reported
1047
+ and previous.runtime_version=p_event->>'runtimeVersion' and previous.channel=p_event->>'channel' then
1048
+ artifact := previous.resolved_update_id; label := previous.update_label;
1049
+ end if;
1050
+ if artifact is not null then kind := 'ota'; end if;
1051
+ end if;
1052
+ before_version := jsonb_build_object('runtime',previous.runtime_version,'channel',previous.channel,
1053
+ 'nativeVersion',previous.native_version,'nativeBuild',previous.native_build,'kind',previous.launch_kind,
1054
+ 'updateId',coalesce(previous.resolved_update_id,previous.reported_update_id));
1055
+ after_version := jsonb_build_object('runtime',p_event->>'runtimeVersion','channel',p_event->>'channel',
1056
+ 'nativeVersion',p_event->>'nativeVersion','nativeBuild',p_event->>'nativeBuild','kind',kind,
1057
+ 'updateId',coalesce(artifact,reported));
1058
+ update public.ota_device_state set
1059
+ runtime_version=p_event->>'runtimeVersion',channel=p_event->>'channel',
1060
+ embedded_update_id=case when kind='embedded' then reported else previous.embedded_update_id end,
1061
+ current_update_id=(select update_id from public.ota_updates where update_id=artifact),
1062
+ served_manifest_id=case when kind<>'embedded' then reported end,
1063
+ reported_update_id=reported,resolved_update_id=artifact,update_label=label,launch_kind=kind,
1064
+ native_version=p_event->>'nativeVersion',native_build=p_event->>'nativeBuild',
1065
+ emergency_launch=(p_event->>'isEmergencyLaunch')::boolean,observed_at=(p_event->>'observedAt')::timestamptz,
1066
+ last_event_id=(p_event->>'eventId')::uuid,last_sequence=seq,last_seen_at=receipt
1067
+ where installation_id=previous.installation_id and platform=previous.platform;
1068
+ if previous.last_sequence=0 or before_version is distinct from after_version then
1069
+ insert into public.ota_device_transitions(installation_id,platform,from_runtime,from_update_id,to_runtime,to_update_id,
1070
+ transition_type,occurred_at,event_id,before_state,after_state)
1071
+ values(previous.installation_id,previous.platform,case when previous.last_sequence>0 then previous.runtime_version end,
1072
+ previous.resolved_update_id,p_event->>'runtimeVersion',artifact,
1073
+ case when previous.last_sequence=0 then 'first_seen' else 'version_changed' end,receipt,
1074
+ (p_event->>'eventId')::uuid,case when previous.last_sequence>0 then before_version end,after_version);
1075
+ end if;
1076
+ return query select 'accepted'::text;
1077
+ end $$;
1078
+
1079
+ -- One statement gives the page and version distribution the same database snapshot.
1080
+ create or replace function public.ota_devices_report(p_days integer default 7, p_platform text default null,
1081
+ p_channel text default null, p_runtime text default null, p_offset integer default 0)
1082
+ returns table(report jsonb) language sql stable set search_path=public as $$
1083
+ with filtered as (
1084
+ select * from public.ota_device_state where last_sequence>0
1085
+ and last_seen_at >= now() - make_interval(days => p_days)
1086
+ and (p_platform is null or platform=p_platform)
1087
+ and (p_channel is null or channel=p_channel)
1088
+ and (p_runtime is null or runtime_version=p_runtime)
1089
+ ), versions as (
1090
+ select platform,channel,runtime_version,native_version,native_build,launch_kind,
1091
+ coalesce(resolved_update_id,reported_update_id) as update_id,max(update_label) as update_label,count(*) as installations
1092
+ from filtered group by platform,channel,runtime_version,native_version,native_build,launch_kind,
1093
+ coalesce(resolved_update_id,reported_update_id)
1094
+ ), page as (select * from filtered order by last_seen_at desc,installation_id,platform limit 50 offset p_offset)
1095
+ select jsonb_build_object('total',(select count(*) from filtered),'pageSize',50,
1096
+ 'devices',coalesce((select jsonb_agg(to_jsonb(page) order by last_seen_at desc,installation_id,platform) from page),'[]'::jsonb),
1097
+ 'versions',coalesce((select jsonb_agg(to_jsonb(versions) order by installations desc,platform,channel,runtime_version,update_id) from versions),'[]'::jsonb));
1098
+ $$;
1099
+
1100
+ alter table public.ota_device_state enable row level security;
1101
+ alter table public.ota_device_transitions enable row level security;
1102
+ revoke all on public.ota_device_state, public.ota_device_transitions from public;
1103
+ revoke all on function public.ota_record_heartbeat(jsonb) from public;
1104
+ revoke all on function public.ota_devices_report(integer,text,text,text,integer) from public;
1105
+ do $$ declare role_name text; begin
1106
+ foreach role_name in array array['anon','authenticated'] loop
1107
+ if exists(select 1 from pg_roles where rolname=role_name) then
1108
+ execute format('revoke all on public.ota_device_state, public.ota_device_transitions from %I',role_name);
1109
+ execute format('revoke all on sequence public.ota_device_transitions_id_seq from %I',role_name);
1110
+ execute format('revoke all on function public.ota_record_heartbeat(jsonb) from %I',role_name);
1111
+ execute format('revoke all on function public.ota_devices_report(integer,text,text,text,integer) from %I',role_name);
1112
+ end if;
1113
+ end loop;
1114
+ if exists(select 1 from pg_roles where rolname='service_role') then
1115
+ grant select,insert,update on public.ota_device_state, public.ota_device_transitions to service_role;
1116
+ grant usage,select on sequence public.ota_device_transitions_id_seq to service_role;
1117
+ grant execute on function public.ota_record_heartbeat(jsonb) to service_role;
1118
+ grant execute on function public.ota_devices_report(integer,text,text,text,integer) to service_role;
1119
+ end if;
1120
+ end $$;
1121
+ commit;
1122
+
1123
+ -- Daily device analytics (2026-10-22).
1124
+ -- Apply after 2026-10-19-device-heartbeat.sql. Safe to reapply.
1125
+ -- Existing last_seen_at and transitions cannot reconstruct daily activity.
1126
+ -- Collection starts here; there is intentionally no historical backfill.
1127
+ begin;
1128
+
1129
+ create table if not exists public.ota_device_analytics_metadata (
1130
+ singleton boolean primary key default true check (singleton),
1131
+ collection_started_at timestamptz not null,
1132
+ last_pruned_on date not null
1133
+ );
1134
+
1135
+ create table if not exists public.ota_device_activity_daily (
1136
+ activity_date date not null,
1137
+ installation_id text not null,
1138
+ platform text not null check (platform in ('ios', 'android')),
1139
+ channel text not null,
1140
+ runtime_version text not null,
1141
+ launch_kind text not null check (launch_kind in ('ota', 'embedded', 'unknown')),
1142
+ native_version text,
1143
+ native_build text,
1144
+ reported_update_id uuid,
1145
+ resolved_update_id uuid,
1146
+ emergency_launch boolean not null,
1147
+ first_received_at timestamptz not null,
1148
+ last_received_at timestamptz not null,
1149
+ primary key (activity_date, installation_id, platform)
1150
+ );
1151
+ create index if not exists idx_ota_device_activity_installation
1152
+ on public.ota_device_activity_daily(installation_id, platform, activity_date);
1153
+
1154
+ -- Only installations whose first instrumented heartbeat arrives after collection
1155
+ -- starts enter retention cohorts. Existing installations still count as active.
1156
+ -- Entry dimensions never change when an installation later changes channel/runtime.
1157
+ create table if not exists public.ota_device_activity_cohorts (
1158
+ installation_id text not null,
1159
+ platform text not null check (platform in ('ios', 'android')),
1160
+ first_observed_at timestamptz not null,
1161
+ channel text not null,
1162
+ runtime_version text not null,
1163
+ launch_kind text not null check (launch_kind in ('ota', 'embedded', 'unknown')),
1164
+ primary key (installation_id, platform)
1165
+ );
1166
+ create index if not exists idx_ota_device_activity_cohort_date
1167
+ on public.ota_device_activity_cohorts(first_observed_at);
1168
+
1169
+ -- Callable by a scheduler; heartbeat also invokes it. Only the first successful
1170
+ -- call each UTC day deletes expired rows. Subsequent calls perform no table scan.
1171
+ create or replace function public.ota_prune_device_activity()
1172
+ returns void language plpgsql set search_path = public as $$
1173
+ declare
1174
+ today date := (clock_timestamp() at time zone 'UTC')::date;
1175
+ begin
1176
+ update public.ota_device_analytics_metadata set last_pruned_on = today
1177
+ where singleton and last_pruned_on < today;
1178
+ if not found then return; end if;
1179
+ delete from public.ota_device_activity_daily where activity_date < today - 89;
1180
+ delete from public.ota_device_activity_cohorts
1181
+ where first_observed_at < ((today - 89)::timestamp at time zone 'UTC');
1182
+ end $$;
1183
+
1184
+ create or replace function public.ota_capture_device_activity()
1185
+ returns trigger language plpgsql set search_path = public as $$
1186
+ declare
1187
+ previous_sequence bigint := 0;
1188
+ receipt_day date := (new.last_seen_at at time zone 'UTC')::date;
1189
+ begin
1190
+ if tg_op = 'UPDATE' then previous_sequence := old.last_sequence; end if;
1191
+ -- FK cleanup, ordinary edits, rejected retries, and registration placeholders
1192
+ -- must never manufacture another day of activity.
1193
+ if new.last_sequence <= previous_sequence then return new; end if;
1194
+ perform public.ota_prune_device_activity();
1195
+ if previous_sequence = 0 then
1196
+ insert into public.ota_device_activity_cohorts
1197
+ (installation_id, platform, first_observed_at, channel, runtime_version, launch_kind)
1198
+ values (new.installation_id, new.platform, new.last_seen_at, new.channel, new.runtime_version, new.launch_kind)
1199
+ on conflict (installation_id, platform) do nothing;
1200
+ end if;
1201
+ insert into public.ota_device_activity_daily
1202
+ (activity_date, installation_id, platform, channel, runtime_version, launch_kind,
1203
+ native_version, native_build, reported_update_id, resolved_update_id, emergency_launch,
1204
+ first_received_at, last_received_at)
1205
+ values
1206
+ (receipt_day, new.installation_id, new.platform, new.channel, new.runtime_version, new.launch_kind,
1207
+ new.native_version, new.native_build, new.reported_update_id, new.resolved_update_id, new.emergency_launch,
1208
+ new.last_seen_at, new.last_seen_at)
1209
+ on conflict (activity_date, installation_id, platform) do update set
1210
+ channel = excluded.channel, runtime_version = excluded.runtime_version, launch_kind = excluded.launch_kind,
1211
+ native_version = excluded.native_version, native_build = excluded.native_build,
1212
+ reported_update_id = excluded.reported_update_id, resolved_update_id = excluded.resolved_update_id,
1213
+ emergency_launch = excluded.emergency_launch, last_received_at = excluded.last_received_at;
1214
+ return new;
1215
+ end $$;
1216
+
1217
+ drop trigger if exists trg_ota_capture_device_activity on public.ota_device_state;
1218
+ create trigger trg_ota_capture_device_activity after insert or update on public.ota_device_state
1219
+ for each row execute function public.ota_capture_device_activity();
1220
+
1221
+ insert into public.ota_device_analytics_metadata(singleton, collection_started_at, last_pruned_on)
1222
+ values (true, clock_timestamp(), (clock_timestamp() at time zone 'UTC')::date)
1223
+ on conflict (singleton) do nothing;
1224
+
1225
+ -- Keep the original five-argument report RPC intact for older consumers.
1226
+ -- One SQL statement gives every chart and the device page a consistent snapshot.
1227
+ create or replace function public.ota_devices_report_v2(
1228
+ p_days integer default 7, p_platform text default null, p_channel text default null,
1229
+ p_runtime text default null, p_offset integer default 0,
1230
+ p_launch_kind text default null, p_search text default null)
1231
+ returns table(report jsonb) language sql stable set search_path = public as $$
1232
+ with parameters as (
1233
+ select (now() at time zone 'UTC')::date as today,
1234
+ (now() at time zone 'UTC')::date - (p_days - 1) as first_day,
1235
+ now() - make_interval(days => p_days) as window_start,
1236
+ m.collection_started_at,
1237
+ greatest((m.collection_started_at at time zone 'UTC')::date,
1238
+ (now() at time zone 'UTC')::date - 89) as retained_from
1239
+ from public.ota_device_analytics_metadata m where singleton
1240
+ ), recent as (
1241
+ select s.* from public.ota_device_state s, parameters p
1242
+ where s.last_sequence > 0 and s.last_seen_at >= p.window_start
1243
+ ), filtered as (
1244
+ select * from recent
1245
+ where (p_platform is null or platform = p_platform)
1246
+ and (p_channel is null or channel = p_channel)
1247
+ and (p_runtime is null or runtime_version = p_runtime)
1248
+ and (p_launch_kind is null or launch_kind = p_launch_kind)
1249
+ and (p_search is null or position(lower(p_search) in lower(installation_id)) > 0)
1250
+ ), versions as (
1251
+ select platform, channel, runtime_version, native_version, native_build, launch_kind,
1252
+ coalesce(resolved_update_id, reported_update_id) as update_id,
1253
+ max(update_label) as update_label, count(*) as installations
1254
+ from filtered group by platform, channel, runtime_version, native_version, native_build,
1255
+ launch_kind, coalesce(resolved_update_id, reported_update_id)
1256
+ ), page as (
1257
+ select * from filtered order by last_seen_at desc, installation_id, platform limit 50 offset p_offset
1258
+ ), daily as (
1259
+ select d.* from public.ota_device_activity_daily d, parameters p
1260
+ where d.activity_date between greatest(p.first_day, p.retained_from) and p.today
1261
+ ), filtered_daily as (
1262
+ select d.* from daily d
1263
+ where (p_platform is null or d.platform = p_platform)
1264
+ and (p_channel is null or d.channel = p_channel)
1265
+ and (p_runtime is null or d.runtime_version = p_runtime)
1266
+ and (p_launch_kind is null or d.launch_kind = p_launch_kind)
1267
+ and (p_search is null or position(lower(p_search) in lower(d.installation_id)) > 0)
1268
+ ), calendar as (
1269
+ select p.first_day + n as date,
1270
+ case when p.first_day + n < p.retained_from then 'unavailable'
1271
+ when p.first_day + n = p.today
1272
+ or ((p.first_day + n)::timestamp at time zone 'UTC') < p.collection_started_at then 'partial'
1273
+ else 'complete' end as coverage
1274
+ from parameters p cross join generate_series(0, p_days - 1) n
1275
+ ), day_counts as (
1276
+ select d.activity_date, count(*) as active,
1277
+ count(*) filter (where (c.first_observed_at at time zone 'UTC')::date = d.activity_date) as newly_observed
1278
+ from filtered_daily d left join public.ota_device_activity_cohorts c
1279
+ on c.installation_id = d.installation_id and c.platform = d.platform
1280
+ group by d.activity_date
1281
+ ), activity as (
1282
+ select c.date, c.coverage,
1283
+ case when c.coverage <> 'unavailable' then coalesce(d.active, 0) end as active,
1284
+ case when c.coverage <> 'unavailable' then coalesce(d.newly_observed, 0) end as newly_observed
1285
+ from calendar c left join day_counts d on c.date = d.activity_date
1286
+ ), cohort_source as (
1287
+ select c.*, (c.first_observed_at at time zone 'UTC')::date as first_day,
1288
+ date_trunc('week', c.first_observed_at at time zone 'UTC')::date as week_start
1289
+ from public.ota_device_activity_cohorts c, parameters p
1290
+ where c.first_observed_at >= p.collection_started_at
1291
+ and (c.first_observed_at at time zone 'UTC')::date between p.retained_from and p.today
1292
+ ), cohort_members as (
1293
+ select * from cohort_source
1294
+ where (p_platform is null or platform = p_platform)
1295
+ and (p_channel is null or channel = p_channel)
1296
+ and (p_runtime is null or runtime_version = p_runtime)
1297
+ and (p_launch_kind is null or launch_kind = p_launch_kind)
1298
+ and (p_search is null or position(lower(p_search) in lower(installation_id)) > 0)
1299
+ ), cohort_sizes as (
1300
+ select week_start, count(*) as installations from cohort_members group by week_start
1301
+ ), retention_members as (
1302
+ select c.week_start, n.day,
1303
+ (n.day = 0 or c.first_day + n.day < p.today) as eligible,
1304
+ exists (select 1 from public.ota_device_activity_daily d
1305
+ where d.installation_id = c.installation_id and d.platform = c.platform
1306
+ and d.activity_date = c.first_day + n.day) as returned
1307
+ from cohort_members c cross join (values (0), (1), (7), (14), (30)) n(day)
1308
+ cross join parameters p
1309
+ ), retention_counts as (
1310
+ select week_start, day, count(*) filter (where eligible) as eligible,
1311
+ count(*) filter (where eligible and returned) as retained
1312
+ from retention_members group by week_start, day
1313
+ ), retention_rows as (
1314
+ select c.week_start, c.installations,
1315
+ jsonb_agg(jsonb_build_object('day', r.day, 'eligibleInstallations', r.eligible,
1316
+ 'retainedInstallations', case when r.eligible > 0 then r.retained end,
1317
+ 'rate', case when r.eligible > 0 then r.retained::numeric / r.eligible end) order by r.day) as cells
1318
+ from cohort_sizes c join retention_counts r using (week_start) group by c.week_start, c.installations
1319
+ ), adoption as (
1320
+ select date_trunc('week', first_seen_at at time zone 'UTC')::date as week_start,
1321
+ count(*) as installations,
1322
+ count(*) filter (where launch_kind = 'ota') as ota,
1323
+ count(*) filter (where launch_kind = 'embedded') as embedded,
1324
+ count(*) filter (where launch_kind = 'unknown') as unknown
1325
+ from filtered group by date_trunc('week', first_seen_at at time zone 'UTC')::date
1326
+ ), option_source as (
1327
+ select platform, channel, runtime_version, launch_kind from recent
1328
+ union select platform, channel, runtime_version, launch_kind from daily
1329
+ union select platform, channel, runtime_version, launch_kind from cohort_source
1330
+ )
1331
+ select jsonb_build_object(
1332
+ 'total', (select count(*) from filtered), 'pageSize', 50, 'offset', p_offset,
1333
+ 'devices', coalesce((select jsonb_agg(to_jsonb(page) order by last_seen_at desc, installation_id, platform) from page), '[]'::jsonb),
1334
+ 'versions', coalesce((select jsonb_agg(to_jsonb(versions) order by installations desc, platform, channel, runtime_version,
1335
+ native_version, native_build, launch_kind, update_id) from versions), '[]'::jsonb),
1336
+ 'filters', jsonb_build_object('days', p_days, 'platform', p_platform, 'channel', p_channel,
1337
+ 'runtime', p_runtime, 'launchKind', p_launch_kind, 'search', p_search),
1338
+ 'options', jsonb_build_object(
1339
+ 'platforms', coalesce((select jsonb_agg(v order by v) from (select distinct platform as v from option_source) t), '[]'::jsonb),
1340
+ 'channels', coalesce((select jsonb_agg(v order by v) from (select distinct channel as v from option_source) t), '[]'::jsonb),
1341
+ 'runtimes', coalesce((select jsonb_agg(v order by v) from (select distinct runtime_version as v from option_source) t), '[]'::jsonb),
1342
+ 'launchKinds', coalesce((select jsonb_agg(v order by v) from (select distinct launch_kind as v from option_source) t), '[]'::jsonb)),
1343
+ 'summary', (select jsonb_build_object('activeInstallations', count(*),
1344
+ 'newInstallations', count(*) filter (where first_seen_at >= (select window_start from parameters)),
1345
+ 'otaInstallations', count(*) filter (where launch_kind = 'ota'),
1346
+ 'embeddedInstallations', count(*) filter (where launch_kind = 'embedded'),
1347
+ 'unknownInstallations', count(*) filter (where launch_kind = 'unknown'),
1348
+ 'emergencyInstallations', count(*) filter (where emergency_launch),
1349
+ 'reportedVersions', (select count(*) from versions)) from filtered),
1350
+ 'activity', coalesce((select jsonb_agg(jsonb_build_object('date', date, 'activeInstallations', active,
1351
+ 'newInstallations', newly_observed, 'coverage', coverage) order by date) from activity), '[]'::jsonb),
1352
+ 'adoptionCohorts', coalesce((select jsonb_agg(jsonb_build_object('weekStart', week_start, 'installations', installations,
1353
+ 'otaInstallations', ota, 'embeddedInstallations', embedded, 'unknownInstallations', unknown) order by week_start) from adoption), '[]'::jsonb),
1354
+ 'cohorts', coalesce((select jsonb_agg(jsonb_build_object('weekStart', week_start, 'installations', installations,
1355
+ 'cells', cells) order by week_start) from retention_rows), '[]'::jsonb),
1356
+ 'coverage', (select jsonb_build_object('collectionStartedAt', collection_started_at, 'retainedFrom', retained_from,
1357
+ 'timezone', 'UTC', 'retentionDays', 90, 'cohortWindowDays', 90, 'activityBasis', 'accepted-heartbeat-receipt',
1358
+ 'cohortBasis', 'first-recorded-heartbeat', 'cohortFilters', 'entry-state', 'todayIsPartial', true,
1359
+ 'generatedAt', now(), 'windowStartedAt', window_start) from parameters)
1360
+ );
1361
+ $$;
1362
+
1363
+ alter table public.ota_device_analytics_metadata enable row level security;
1364
+ alter table public.ota_device_activity_daily enable row level security;
1365
+ alter table public.ota_device_activity_cohorts enable row level security;
1366
+ revoke all on public.ota_device_analytics_metadata, public.ota_device_activity_daily, public.ota_device_activity_cohorts from public;
1367
+ revoke all on function public.ota_prune_device_activity() from public;
1368
+ revoke all on function public.ota_capture_device_activity() from public;
1369
+ revoke all on function public.ota_devices_report_v2(integer,text,text,text,integer,text,text) from public;
1370
+ do $$ declare role_name text; begin
1371
+ foreach role_name in array array['anon', 'authenticated'] loop
1372
+ if exists(select 1 from pg_roles where rolname = role_name) then
1373
+ execute format('revoke all on public.ota_device_analytics_metadata, public.ota_device_activity_daily, public.ota_device_activity_cohorts from %I', role_name);
1374
+ execute format('revoke all on function public.ota_prune_device_activity() from %I', role_name);
1375
+ execute format('revoke all on function public.ota_capture_device_activity() from %I', role_name);
1376
+ execute format('revoke all on function public.ota_devices_report_v2(integer,text,text,text,integer,text,text) from %I', role_name);
1377
+ end if;
1378
+ end loop;
1379
+ if exists(select 1 from pg_roles where rolname = 'service_role') then
1380
+ grant select, update on public.ota_device_analytics_metadata to service_role;
1381
+ grant select, insert, update, delete on public.ota_device_activity_daily, public.ota_device_activity_cohorts to service_role;
1382
+ grant execute on function public.ota_prune_device_activity() to service_role;
1383
+ grant execute on function public.ota_capture_device_activity() to service_role;
1384
+ grant execute on function public.ota_devices_report_v2(integer,text,text,text,integer,text,text) to service_role;
1385
+ end if;
1386
+ end $$;
1387
+ commit;
1388
+
1389
+ -- Device version metadata (2026-10-22).
1390
+ -- Apply after 2026-10-22-device-analytics.sql. Safe to reapply.
1391
+ -- Version names come from manifest metadata, never the publication message.
1392
+ begin;
1393
+
1394
+ create or replace function public.ota_devices_report_v2(
1395
+ p_days integer default 7, p_platform text default null, p_channel text default null,
1396
+ p_runtime text default null, p_offset integer default 0,
1397
+ p_launch_kind text default null, p_search text default null)
1398
+ returns table(report jsonb) language sql stable set search_path = public as $$
1399
+ with parameters as (
1400
+ select (now() at time zone 'UTC')::date as today,
1401
+ (now() at time zone 'UTC')::date - (p_days - 1) as first_day,
1402
+ now() - make_interval(days => p_days) as window_start,
1403
+ m.collection_started_at,
1404
+ greatest((m.collection_started_at at time zone 'UTC')::date,
1405
+ (now() at time zone 'UTC')::date - 89) as retained_from
1406
+ from public.ota_device_analytics_metadata m where singleton
1407
+ ), recent as (
1408
+ select s.* from public.ota_device_state s, parameters p
1409
+ where s.last_sequence > 0 and s.last_seen_at >= p.window_start
1410
+ ), filtered as (
1411
+ select * from recent
1412
+ where (p_platform is null or platform = p_platform)
1413
+ and (p_channel is null or channel = p_channel)
1414
+ and (p_runtime is null or runtime_version = p_runtime)
1415
+ and (p_launch_kind is null or launch_kind = p_launch_kind)
1416
+ and (p_search is null or position(lower(p_search) in lower(installation_id)) > 0)
1417
+ ), version_counts as (
1418
+ select platform, channel, runtime_version, native_version, native_build, launch_kind,
1419
+ coalesce(resolved_update_id, reported_update_id) as update_id,
1420
+ max(update_label) as update_label, count(*) as installations
1421
+ from filtered group by platform, channel, runtime_version, native_version, native_build,
1422
+ launch_kind, coalesce(resolved_update_id, reported_update_id)
1423
+ ), versions as (
1424
+ select v.*, case when v.launch_kind = 'ota' then coalesce(
1425
+ case when jsonb_typeof(u.manifest #> '{extra,expoClient,version}') = 'string'
1426
+ then nullif(btrim(u.manifest #>> '{extra,expoClient,version}'), '') end,
1427
+ case when jsonb_typeof(u.manifest #> '{expoClient,version}') = 'string'
1428
+ then nullif(btrim(u.manifest #>> '{expoClient,version}'), '') end
1429
+ ) when v.launch_kind = 'embedded' then coalesce(nullif(btrim(e.app_version), ''), v.native_version)
1430
+ else null end as app_version
1431
+ from version_counts v
1432
+ left join public.ota_updates u on v.launch_kind = 'ota' and u.update_id = v.update_id
1433
+ and u.runtime_version = v.runtime_version and u.channel = v.channel and u.platform = v.platform
1434
+ left join public.ota_embedded_updates e on v.launch_kind = 'embedded' and e.embedded_update_id = v.update_id
1435
+ and e.channel = v.channel and e.platform = v.platform
1436
+ ), page as (
1437
+ select * from filtered order by last_seen_at desc, installation_id, platform limit 50 offset p_offset
1438
+ ), daily as (
1439
+ select d.* from public.ota_device_activity_daily d, parameters p
1440
+ where d.activity_date between greatest(p.first_day, p.retained_from) and p.today
1441
+ ), filtered_daily as (
1442
+ select d.* from daily d
1443
+ where (p_platform is null or d.platform = p_platform)
1444
+ and (p_channel is null or d.channel = p_channel)
1445
+ and (p_runtime is null or d.runtime_version = p_runtime)
1446
+ and (p_launch_kind is null or d.launch_kind = p_launch_kind)
1447
+ and (p_search is null or position(lower(p_search) in lower(d.installation_id)) > 0)
1448
+ ), calendar as (
1449
+ select p.first_day + n as date,
1450
+ case when p.first_day + n < p.retained_from then 'unavailable'
1451
+ when p.first_day + n = p.today
1452
+ or ((p.first_day + n)::timestamp at time zone 'UTC') < p.collection_started_at then 'partial'
1453
+ else 'complete' end as coverage
1454
+ from parameters p cross join generate_series(0, p_days - 1) n
1455
+ ), day_counts as (
1456
+ select d.activity_date, count(*) as active,
1457
+ count(*) filter (where (c.first_observed_at at time zone 'UTC')::date = d.activity_date) as newly_observed
1458
+ from filtered_daily d left join public.ota_device_activity_cohorts c
1459
+ on c.installation_id = d.installation_id and c.platform = d.platform
1460
+ group by d.activity_date
1461
+ ), activity as (
1462
+ select c.date, c.coverage,
1463
+ case when c.coverage <> 'unavailable' then coalesce(d.active, 0) end as active,
1464
+ case when c.coverage <> 'unavailable' then coalesce(d.newly_observed, 0) end as newly_observed
1465
+ from calendar c left join day_counts d on c.date = d.activity_date
1466
+ ), cohort_source as (
1467
+ select c.*, (c.first_observed_at at time zone 'UTC')::date as first_day,
1468
+ date_trunc('week', c.first_observed_at at time zone 'UTC')::date as week_start
1469
+ from public.ota_device_activity_cohorts c, parameters p
1470
+ where c.first_observed_at >= p.collection_started_at
1471
+ and (c.first_observed_at at time zone 'UTC')::date between p.retained_from and p.today
1472
+ ), cohort_members as (
1473
+ select * from cohort_source
1474
+ where (p_platform is null or platform = p_platform)
1475
+ and (p_channel is null or channel = p_channel)
1476
+ and (p_runtime is null or runtime_version = p_runtime)
1477
+ and (p_launch_kind is null or launch_kind = p_launch_kind)
1478
+ and (p_search is null or position(lower(p_search) in lower(installation_id)) > 0)
1479
+ ), cohort_sizes as (
1480
+ select week_start, count(*) as installations from cohort_members group by week_start
1481
+ ), retention_members as (
1482
+ select c.week_start, n.day,
1483
+ (n.day = 0 or c.first_day + n.day < p.today) as eligible,
1484
+ exists (select 1 from public.ota_device_activity_daily d
1485
+ where d.installation_id = c.installation_id and d.platform = c.platform
1486
+ and d.activity_date = c.first_day + n.day) as returned
1487
+ from cohort_members c cross join (values (0), (1), (7), (14), (30)) n(day)
1488
+ cross join parameters p
1489
+ ), retention_counts as (
1490
+ select week_start, day, count(*) filter (where eligible) as eligible,
1491
+ count(*) filter (where eligible and returned) as retained
1492
+ from retention_members group by week_start, day
1493
+ ), retention_rows as (
1494
+ select c.week_start, c.installations,
1495
+ jsonb_agg(jsonb_build_object('day', r.day, 'eligibleInstallations', r.eligible,
1496
+ 'retainedInstallations', case when r.eligible > 0 then r.retained end,
1497
+ 'rate', case when r.eligible > 0 then r.retained::numeric / r.eligible end) order by r.day) as cells
1498
+ from cohort_sizes c join retention_counts r using (week_start) group by c.week_start, c.installations
1499
+ ), adoption as (
1500
+ select date_trunc('week', first_seen_at at time zone 'UTC')::date as week_start,
1501
+ count(*) as installations,
1502
+ count(*) filter (where launch_kind = 'ota') as ota,
1503
+ count(*) filter (where launch_kind = 'embedded') as embedded,
1504
+ count(*) filter (where launch_kind = 'unknown') as unknown
1505
+ from filtered group by date_trunc('week', first_seen_at at time zone 'UTC')::date
1506
+ ), option_source as (
1507
+ select platform, channel, runtime_version, launch_kind from recent
1508
+ union select platform, channel, runtime_version, launch_kind from daily
1509
+ union select platform, channel, runtime_version, launch_kind from cohort_source
1510
+ )
1511
+ select jsonb_build_object(
1512
+ 'total', (select count(*) from filtered), 'pageSize', 50, 'offset', p_offset,
1513
+ 'devices', coalesce((select jsonb_agg(to_jsonb(page) order by last_seen_at desc, installation_id, platform) from page), '[]'::jsonb),
1514
+ 'versions', coalesce((select jsonb_agg(to_jsonb(versions) order by installations desc, platform, channel, runtime_version,
1515
+ native_version, native_build, launch_kind, update_id) from versions), '[]'::jsonb),
1516
+ 'filters', jsonb_build_object('days', p_days, 'platform', p_platform, 'channel', p_channel,
1517
+ 'runtime', p_runtime, 'launchKind', p_launch_kind, 'search', p_search),
1518
+ 'options', jsonb_build_object(
1519
+ 'platforms', coalesce((select jsonb_agg(v order by v) from (select distinct platform as v from option_source) t), '[]'::jsonb),
1520
+ 'channels', coalesce((select jsonb_agg(v order by v) from (select distinct channel as v from option_source) t), '[]'::jsonb),
1521
+ 'runtimes', coalesce((select jsonb_agg(v order by v) from (select distinct runtime_version as v from option_source) t), '[]'::jsonb),
1522
+ 'launchKinds', coalesce((select jsonb_agg(v order by v) from (select distinct launch_kind as v from option_source) t), '[]'::jsonb)),
1523
+ 'summary', (select jsonb_build_object('activeInstallations', count(*),
1524
+ 'newInstallations', count(*) filter (where first_seen_at >= (select window_start from parameters)),
1525
+ 'otaInstallations', count(*) filter (where launch_kind = 'ota'),
1526
+ 'embeddedInstallations', count(*) filter (where launch_kind = 'embedded'),
1527
+ 'unknownInstallations', count(*) filter (where launch_kind = 'unknown'),
1528
+ 'emergencyInstallations', count(*) filter (where emergency_launch),
1529
+ 'reportedVersions', (select count(*) from versions)) from filtered),
1530
+ 'activity', coalesce((select jsonb_agg(jsonb_build_object('date', date, 'activeInstallations', active,
1531
+ 'newInstallations', newly_observed, 'coverage', coverage) order by date) from activity), '[]'::jsonb),
1532
+ 'adoptionCohorts', coalesce((select jsonb_agg(jsonb_build_object('weekStart', week_start, 'installations', installations,
1533
+ 'otaInstallations', ota, 'embeddedInstallations', embedded, 'unknownInstallations', unknown) order by week_start) from adoption), '[]'::jsonb),
1534
+ 'cohorts', coalesce((select jsonb_agg(jsonb_build_object('weekStart', week_start, 'installations', installations,
1535
+ 'cells', cells) order by week_start) from retention_rows), '[]'::jsonb),
1536
+ 'coverage', (select jsonb_build_object('collectionStartedAt', collection_started_at, 'retainedFrom', retained_from,
1537
+ 'timezone', 'UTC', 'retentionDays', 90, 'cohortWindowDays', 90, 'activityBasis', 'accepted-heartbeat-receipt',
1538
+ 'cohortBasis', 'first-recorded-heartbeat', 'cohortFilters', 'entry-state', 'todayIsPartial', true,
1539
+ 'generatedAt', now(), 'windowStartedAt', window_start) from parameters)
1540
+ );
1541
+ $$;
1542
+
1543
+ commit;
1544
+
1545
+ -- Apply after device-version-metadata. Existing releases remain public.
1546
+ begin;
1547
+ -- Targeted releases coexist with their public fallback.
1548
+ drop index if exists public.idx_ota_updates_one_active_per_scope;
1549
+ alter table public.ota_updates
1550
+ add column if not exists audience_mode text not null default 'all' check (audience_mode in ('all','devices')),
1551
+ add column if not exists audience_installation_ids text[] not null default '{}',
1552
+ add column if not exists audience_device_ids text[] not null default '{}',
1553
+ add column if not exists audience_version integer not null default 1 check (audience_version > 0);
1554
+ alter table public.ota_device_state add column if not exists device_id text check (device_id ~ '^[0-9a-f]{64}$');
1555
+ create index if not exists idx_ota_device_state_device on public.ota_device_state(device_id,platform);
1556
+ create table if not exists public.ota_named_devices (
1557
+ device_id text primary key check (device_id ~ '^[0-9a-f]{64}$'),
1558
+ name text not null check (length(name) between 1 and 80 and name = btrim(name) and name !~ '[[:cntrl:]]')
1559
+ );
1560
+ alter table public.ota_named_devices enable row level security;
1561
+ revoke all on public.ota_named_devices from public;
1562
+
1563
+ create or replace function public.ota_latest_eligible_update(p_runtime text, p_channel text, p_platform text,
1564
+ p_installation text default null, p_device text default null)
1565
+ returns setof public.ota_updates language sql stable set search_path=public as $$
1566
+ select * from public.ota_updates where runtime_version=p_runtime and channel=p_channel and platform=p_platform and is_active
1567
+ and (audience_mode='all' or (audience_mode='devices' and
1568
+ (p_installation=any(audience_installation_ids) or p_device=any(audience_device_ids))))
1569
+ order by created_at desc, update_id desc limit 1;
1570
+ $$;
1571
+
1572
+ create or replace function public.ota_replace_audience(p_update uuid, p_mode text, p_installations jsonb,
1573
+ p_devices jsonb, p_version integer)
1574
+ returns setof public.ota_updates language plpgsql set search_path=public as $$
1575
+ declare ids text[]; devices text[];
1576
+ begin
1577
+ perform public.assert_ota_distribution_mutation_allowed('change update audience');
1578
+ if p_mode is null or p_mode not in ('all','devices') or jsonb_typeof(p_installations) is distinct from 'array'
1579
+ or jsonb_typeof(p_devices) is distinct from 'array' then raise exception 'INVALID_AUDIENCE'; end if;
1580
+ select coalesce(array_agg(distinct value),'{}') into ids from jsonb_array_elements_text(p_installations);
1581
+ select coalesce(array_agg(distinct value),'{}') into devices from jsonb_array_elements_text(p_devices);
1582
+ if cardinality(ids)>100 or cardinality(devices)>100 or
1583
+ exists(select 1 from unnest(ids) id where id is null or id !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$') or
1584
+ exists(select 1 from unnest(devices) id where id is null or id !~ '^[0-9a-f]{64}$') or
1585
+ (p_mode='devices' and cardinality(ids)+cardinality(devices)=0)
1586
+ then raise exception 'INVALID_AUDIENCE'; end if;
1587
+ return query update public.ota_updates set audience_mode=p_mode, audience_installation_ids=ids,
1588
+ audience_device_ids=devices,audience_version=audience_version+1
1589
+ where update_id=p_update and audience_version=p_version returning *;
1590
+ if not found then raise exception 'AUDIENCE_CONFLICT'; end if;
1591
+ end $$;
1592
+
1593
+ create or replace function public.ota_record_heartbeat(p_event jsonb)
1594
+ returns table(result text) language plpgsql set search_path = public as $$
1595
+ declare
1596
+ previous public.ota_device_state%rowtype;
1597
+ artifact uuid;
1598
+ label text;
1599
+ kind text;
1600
+ before_version jsonb;
1601
+ after_version jsonb;
1602
+ seq bigint := (p_event->>'sequence')::bigint;
1603
+ reported uuid := (p_event->>'updateId')::uuid;
1604
+ receipt timestamptz;
1605
+ begin
1606
+ if seq < 1 or seq > 9007199254740991 then raise exception 'INVALID_SEQUENCE'; end if;
1607
+ insert into public.ota_device_state(installation_id,platform,runtime_version,channel)
1608
+ values(p_event->>'installationId',p_event->>'platform',p_event->>'runtimeVersion',p_event->>'channel')
1609
+ on conflict (installation_id,platform) do nothing;
1610
+ select * into strict previous from public.ota_device_state
1611
+ where installation_id=p_event->>'installationId' and platform=p_event->>'platform' for update;
1612
+ if seq < previous.last_sequence then return query select 'stale'::text; return; end if;
1613
+ if seq = previous.last_sequence then
1614
+ if previous.last_event_id = (p_event->>'eventId')::uuid then
1615
+ return query select 'duplicate'::text; return;
1616
+ end if;
1617
+ raise exception 'HEARTBEAT_SEQUENCE_CONFLICT';
1618
+ end if;
1619
+ receipt := greatest(previous.last_seen_at, clock_timestamp());
1620
+ kind := case when (p_event->>'isEmbeddedLaunch')::boolean then 'embedded' else 'unknown' end;
1621
+ if kind <> 'embedded' and reported is not null then
1622
+ select u.update_id,u.comment into artifact,label from public.ota_updates u
1623
+ where u.runtime_version=p_event->>'runtimeVersion' and u.channel=p_event->>'channel' and u.platform=p_event->>'platform'
1624
+ and (u.update_id=reported or exists(select 1 from public.ota_served_manifest_log m
1625
+ where m.served_manifest_id=reported and m.update_id=u.update_id and m.runtime_version=u.runtime_version
1626
+ and m.channel=u.channel and m.platform=u.platform))
1627
+ order by (u.update_id=reported) asc limit 1;
1628
+ if artifact is null and previous.launch_kind='ota' and previous.reported_update_id=reported
1629
+ and previous.runtime_version=p_event->>'runtimeVersion' and previous.channel=p_event->>'channel' then
1630
+ artifact := previous.resolved_update_id; label := previous.update_label;
1631
+ end if;
1632
+ if artifact is not null then kind := 'ota'; end if;
1633
+ end if;
1634
+ before_version := jsonb_build_object('runtime',previous.runtime_version,'channel',previous.channel,
1635
+ 'nativeVersion',previous.native_version,'nativeBuild',previous.native_build,'kind',previous.launch_kind,
1636
+ 'updateId',coalesce(previous.resolved_update_id,previous.reported_update_id));
1637
+ after_version := jsonb_build_object('runtime',p_event->>'runtimeVersion','channel',p_event->>'channel',
1638
+ 'nativeVersion',p_event->>'nativeVersion','nativeBuild',p_event->>'nativeBuild','kind',kind,
1639
+ 'updateId',coalesce(artifact,reported));
1640
+ update public.ota_device_state set
1641
+ device_id=coalesce(p_event->>'deviceId',previous.device_id),
1642
+ runtime_version=p_event->>'runtimeVersion',channel=p_event->>'channel',
1643
+ embedded_update_id=case when kind='embedded' then reported else previous.embedded_update_id end,
1644
+ current_update_id=(select update_id from public.ota_updates where update_id=artifact),
1645
+ served_manifest_id=case when kind<>'embedded' then reported end,
1646
+ reported_update_id=reported,resolved_update_id=artifact,update_label=label,launch_kind=kind,
1647
+ native_version=p_event->>'nativeVersion',native_build=p_event->>'nativeBuild',
1648
+ emergency_launch=(p_event->>'isEmergencyLaunch')::boolean,observed_at=(p_event->>'observedAt')::timestamptz,
1649
+ last_event_id=(p_event->>'eventId')::uuid,last_sequence=seq,last_seen_at=receipt
1650
+ where installation_id=previous.installation_id and platform=previous.platform;
1651
+ if previous.last_sequence=0 or before_version is distinct from after_version then
1652
+ insert into public.ota_device_transitions(installation_id,platform,from_runtime,from_update_id,to_runtime,to_update_id,
1653
+ transition_type,occurred_at,event_id,before_state,after_state)
1654
+ values(previous.installation_id,previous.platform,case when previous.last_sequence>0 then previous.runtime_version end,
1655
+ previous.resolved_update_id,p_event->>'runtimeVersion',artifact,
1656
+ case when previous.last_sequence=0 then 'first_seen' else 'version_changed' end,receipt,
1657
+ (p_event->>'eventId')::uuid,case when previous.last_sequence>0 then before_version end,after_version);
1658
+ end if;
1659
+ return query select 'accepted'::text;
1660
+ end $$;
1661
+
1662
+
1663
+ revoke all on function public.ota_latest_eligible_update(text,text,text,text,text) from public;
1664
+ revoke all on function public.ota_replace_audience(uuid,text,jsonb,jsonb,integer) from public;
1665
+ do $$ begin
1666
+ if exists(select 1 from pg_roles where rolname='service_role') then
1667
+ grant all on public.ota_named_devices to service_role;
1668
+ grant execute on function public.ota_latest_eligible_update(text,text,text,text,text) to service_role;
1669
+ grant execute on function public.ota_replace_audience(uuid,text,jsonb,jsonb,integer) to service_role;
1670
+ drop policy if exists ota_named_devices_service on public.ota_named_devices;
1671
+ create policy ota_named_devices_service on public.ota_named_devices to service_role using (true) with check (true);
1672
+ end if;
1673
+ end $$;
1674
+ commit;
1675
+
1676
+ -- Atomic audience activation and incident deactivation (2026-10-22).
1677
+ -- Apply after 2026-10-22-device-targeting.sql. Repeatable; no release backfill.
1678
+ begin;
1679
+
1680
+ -- JS OTA forcing is distinct from asking for a new binary from the store.
1681
+ insert into public.ota_guard_actions (action_key)
1682
+ values ('ota-force-update')
1683
+ on conflict (action_key) do nothing;
1684
+
1685
+ -- Audience changes and activations take the existing distribution advisory lock
1686
+ -- before any row lock. Evaluate NEW.audience_mode in the activation statement,
1687
+ -- rather than trusting an earlier application read followed by separate writes.
1688
+ create or replace function public.ota_activate_audience()
1689
+ returns trigger language plpgsql security definer set search_path = public, pg_temp as $$
1690
+ begin
1691
+ if new.is_active and new.audience_mode = 'all' then
1692
+ perform public.assert_ota_distribution_mutation_allowed('activating a public OTA update');
1693
+ update public.ota_updates set is_active = false,
1694
+ disabled_at = clock_timestamp(), updated_at = clock_timestamp()
1695
+ where runtime_version = new.runtime_version and channel = new.channel
1696
+ and platform = new.platform and update_id <> new.update_id and is_active;
1697
+ end if;
1698
+ return new;
1699
+ end $$;
1700
+ revoke all on function public.ota_activate_audience() from public;
1701
+ drop trigger if exists trg_ota_updates_activate_audience on public.ota_updates;
1702
+ create trigger trg_ota_updates_activate_audience
1703
+ before insert or update of is_active on public.ota_updates
1704
+ for each row execute function public.ota_activate_audience();
1705
+
1706
+ create or replace function public.guard_ota_channel_distribution()
1707
+ returns trigger
1708
+ language plpgsql
1709
+ security definer
1710
+ set search_path = public, pg_temp
1711
+ as $$
1712
+ declare
1713
+ changes_distribution_state boolean;
1714
+ latest_active public.ota_updates%rowtype;
1715
+ surviving_rollback uuid;
1716
+ begin
1717
+ if tg_op = 'INSERT' then
1718
+ -- Empty channel rows do not distribute an update.
1719
+ changes_distribution_state :=
1720
+ new.latest_update_id is not null
1721
+ or new.active_update_id is not null;
1722
+ else
1723
+ changes_distribution_state :=
1724
+ new.runtime_version is distinct from old.runtime_version
1725
+ or new.channel is distinct from old.channel
1726
+ or new.platform is distinct from old.platform
1727
+ or new.latest_update_id is distinct from old.latest_update_id
1728
+ or new.latest_created_at is distinct from old.latest_created_at
1729
+ or new.latest_created_at_path is distinct from old.latest_created_at_path
1730
+ or new.active_update_id is distinct from old.active_update_id
1731
+ or new.active_changed_at is distinct from old.active_changed_at
1732
+ or new.served_manifest_id is distinct from old.served_manifest_id
1733
+ or new.served_manifest_changed_at
1734
+ is distinct from old.served_manifest_changed_at;
1735
+ end if;
1736
+
1737
+ if not changes_distribution_state then
1738
+ return new;
1739
+ end if;
1740
+
1741
+ -- Clearing every serving pointer only removes distribution and is the
1742
+ -- channel-side part of deactivation. Clearing a rollback pointer while a
1743
+ -- latest pointer remains would promote latest, so it is still guarded.
1744
+ if new.latest_update_id is null and new.active_update_id is null then
1745
+ return new;
1746
+ end if;
1747
+
1748
+ -- Disabling a targeted update can leave an active public fallback. Updating
1749
+ -- pointers to reflect that removal must remain possible while distribution is
1750
+ -- blocked, just as clearing the last active pointer was before targeting.
1751
+ -- Require an already retired pointer; do not permit a promotion or a new scope.
1752
+ if tg_op = 'UPDATE'
1753
+ and new.runtime_version = old.runtime_version
1754
+ and new.channel = old.channel and new.platform = old.platform
1755
+ and (
1756
+ (old.latest_update_id is not null and not exists (
1757
+ select 1 from public.ota_updates where update_id = old.latest_update_id and is_active))
1758
+ or (old.active_update_id is not null and not exists (
1759
+ select 1 from public.ota_updates where update_id = old.active_update_id and is_active))
1760
+ ) then
1761
+ select * into latest_active from public.ota_updates
1762
+ where runtime_version = old.runtime_version and channel = old.channel
1763
+ and platform = old.platform and is_active
1764
+ order by created_at desc, update_id desc limit 1;
1765
+ select update_id into surviving_rollback from public.ota_updates
1766
+ where update_id = old.active_update_id and is_active
1767
+ and update_id is distinct from latest_active.update_id;
1768
+ if new.latest_update_id is not distinct from latest_active.update_id
1769
+ and new.latest_created_at is not distinct from latest_active.created_at
1770
+ and new.latest_created_at_path is not distinct from latest_active.created_at_path
1771
+ and new.active_update_id is not distinct from surviving_rollback then
1772
+ return new;
1773
+ end if;
1774
+ end if;
1775
+
1776
+ perform public.assert_ota_distribution_mutation_allowed(
1777
+ 'changing OTA channel distribution state'
1778
+ );
1779
+ return new;
1780
+ end;
1781
+ $$;
1782
+
1783
+
1784
+ commit;