create-expo-updates-server 0.1.6 → 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 (139) 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/supabase.js +10 -10
  122. package/dist/template/src/server/lib/supabase.test.ts +11 -0
  123. package/dist/template/src/server/manifest/manifest-identity.test.ts +30 -0
  124. package/dist/template/src/server/manifest/manifest-identity.ts +24 -0
  125. package/dist/template/src/server/manifest/manifest-repository.ts +31 -102
  126. package/dist/template/src/server/manifest/manifest-response.ts +1 -1
  127. package/dist/template/templates/expo-app/ota-client/README.md +59 -0
  128. package/dist/template/templates/expo-app/ota-client/controller.js +60 -0
  129. package/dist/template/templates/expo-app/ota-client/device-identity.js +26 -0
  130. package/dist/template/templates/expo-app/ota-client/docs/update-lifecycle.md +52 -0
  131. package/dist/template/templates/expo-app/ota-client/index.d.ts +47 -0
  132. package/dist/template/templates/expo-app/ota-client/index.js +3 -0
  133. package/dist/template/templates/expo-app/ota-client/model/hooks/useOtaUpdates.js +48 -0
  134. package/dist/template/templates/expo-app/ota-client/model/update-controller.js +182 -0
  135. package/dist/template/templates/expo-app/ota-client/runtime.js +112 -0
  136. package/dist/template/templates/expo-app/ota-client/ui/ota-update-gate.js +56 -0
  137. package/dist/template-manifest.json +578 -73
  138. package/lib/cli.mjs +4 -6
  139. package/package.json +1 -1
@@ -0,0 +1,233 @@
1
+ # Installation registry and version adoption
2
+
3
+ For an existing database, apply the migrations in the
4
+ [operations guide](./operations-guide.md#installation-telemetry) before deploying
5
+ the server. Fresh installs use `schema.sql`, which includes telemetry, analytics,
6
+ version metadata, device audiences and atomic activation.
7
+
8
+ Run the existing `npm run configure-app -- ...` workflow. It installs compatible
9
+ `expo-updates`, `expo-application`, `expo-crypto`, `expo-secure-store` and AsyncStorage
10
+ dependencies, creates `ota-client/` and a synchronous `ota-entry.js` bootstrap, and
11
+ preserves the original entry in `ota-client-entry.json`. The configurator also patches
12
+ the root layout/App with `useOtaUpdates` and `OtaUpdateGate`; application authors do not
13
+ have to generate IDs, send heartbeats, or wire update methods by hand. Supported roots
14
+ are described in the [client lifecycle guide](./ota-client-lifecycle.md).
15
+
16
+ Reruns preserve the original entry. Changed generated files require the existing
17
+ `--force` option; review local customizations before replacing them. Custom Android build
18
+ scripts remain intact. Introducing these native modules requires rebuilding the binary
19
+ and using a compatible runtime. An OTA alone cannot add a missing native module.
20
+
21
+ Open `/updates/devices` (the **Установки** link in the admin panel). It shows:
22
+
23
+ - Installation IDs, platform/channel, runtime, native version/build, actual launch
24
+ ID and resolved artifact, emergency launch flag, and last server receipt.
25
+ - Current version distribution among installations seen in the last 24 hours,
26
+ 7 days, or 30 days. Filters cover platform, channel, runtime, launch kind and
27
+ all or part of an installation UUID. Filter options come from recorded data;
28
+ pagination affects only the installation list, not the summary or charts.
29
+ - `embedded`, resolved `ota`, or explicit `unknown` status. A download/check is
30
+ never counted as a launched version. Repeated launches do not multiply devices.
31
+ - UTC daily activity, the current composition of first-seen cohorts, and a
32
+ separate retention matrix with explicit collection coverage.
33
+
34
+ ## Analytics upgrade
35
+
36
+ For a database that already has installation heartbeats, apply the migration
37
+ before deploying the updated server:
38
+
39
+ ```sh
40
+ psql "$DATABASE_URL" -v ON_ERROR_STOP=1 \
41
+ -f docs/migrations/2026-10-22-device-analytics.sql
42
+ ```
43
+
44
+ This follows the database connection convention in the
45
+ [operations guide](./operations-guide.md#installation-telemetry). The migration
46
+ is safe to reapply: it preserves installation state and the original collection
47
+ start. Existing mobile clients with heartbeat support require no new native
48
+ dependencies for these analytics. After deploying the server, open
49
+ `/updates/devices` using an admin session; the page contains the analytics tabs
50
+ and installation registry.
51
+
52
+ The migration creates daily activity facts, immutable cohort entry facts, and
53
+ collection metadata. Accepted heartbeats update the registry and daily facts
54
+ in the same transaction. There is one daily row per installation/platform/UTC
55
+ day, containing the last accepted snapshot for that day. Duplicates and stale
56
+ events do not create activity or change daily timestamps.
57
+
58
+ ## What each view measures
59
+
60
+ | View | Population and time window | Meaning of filters |
61
+ | --- | --- | --- |
62
+ | Summary, versions and installation registry | Last reported state of installations with an accepted heartbeat in the last 24 hours, 7 days or 30 days | Latest reported platform/channel/runtime/launch kind; installation ID search |
63
+ | Daily activity | One point per UTC calendar day, including today, for the selected 1/7/30-day period | Last accepted snapshot of each installation on that day |
64
+ | Adoption cohorts | The same recently active population as the summary, grouped by the UTC week of registry `first_seen_at` | Latest reported state; composition of each group today |
65
+ | Retention cohorts | First instrumented observations recorded since analytics collection began, within the last 90 UTC days, independently of the selected activity period | State at cohort entry; later return activity can occur on any channel/runtime/launch kind |
66
+
67
+ The registry uses a rolling time window, while daily charts use calendar days.
68
+ For example, the 24-hour registry can include a heartbeat from yesterday even
69
+ when the one-day chart shows only today. Channel/runtime/launch-kind changes can
70
+ also make the current-state and daily-snapshot populations differ. Counts refer
71
+ to installations, not unique people or physical phones.
72
+
73
+ Daily **newly observed** counts are first instrumented observations recorded
74
+ after collection starts. An already instrumented installation that sends its
75
+ first post-upgrade heartbeat contributes to daily activity but does not become
76
+ a new installation or a new retention-cohort member. The optional
77
+ `summary.newInstallations` API field instead uses registry `first_seen_at`
78
+ within the selected rolling window, so it can include observations predating
79
+ daily collection.
80
+
81
+ Adoption cohorts are current composition, not retention. They remain useful
82
+ immediately after upgrading because existing installations have registry
83
+ first-seen timestamps, even when no daily history exists yet.
84
+
85
+ ### Retention and coverage
86
+
87
+ Retention is based on accepted heartbeat receipts on exact UTC days since the
88
+ first instrumented observation. D0 is the observed baseline. D1, D7, D14 and D30
89
+ count members with an accepted heartbeat on that exact later day, rather than
90
+ members who returned at any time during the intervening period. Weeks start on
91
+ Monday in UTC.
92
+
93
+ For D1 and later, only members whose target UTC day has ended enter the eligible
94
+ denominator. Each cell includes `eligibleInstallations`, `retainedInstallations`
95
+ and `rate` (a fraction from 0 to 1). A partially mature cohort can therefore
96
+ have a smaller denominator than its total membership. No eligible members means
97
+ `null`, not zero. D0 includes newly observed members today.
98
+
99
+ History before collection is unavailable and is never reconstructed from
100
+ `last_seen_at` or version transitions. The daily chart returns `null` for such
101
+ days. A covered day without accepted heartbeats returns zero. The collection
102
+ start day and today are marked partial. The response exposes
103
+ `coverage.collectionStartedAt`, `retainedFrom`, `timezone`, `retentionDays` and
104
+ `cohortWindowDays` so consumers can show these boundaries.
105
+
106
+ Daily facts and retention cohorts have a 90-day retention window. The first
107
+ accepted heartbeat each UTC day prunes expired facts; subsequent heartbeats
108
+ that day avoid repeating the cleanup. Reports exclude expired days even before
109
+ cleanup runs. An installation with no traffic does not trigger cleanup; a
110
+ scheduler can also call `select public.ota_prune_device_activity();`. Registry
111
+ state and the existing transition log are separate from this retention policy.
112
+
113
+ ## Client contract
114
+
115
+ `POST /api/device-heartbeat`, JSON only, at most 8192 bytes (enforced while reading):
116
+
117
+ ```json
118
+ {
119
+ "installationId": "b1c01662-c4e1-41a0-8556-a6c2a9dee467",
120
+ "eventId": "d28a640f-f4c3-47ae-9044-58a950ad6d38",
121
+ "sequence": 1,
122
+ "observedAt": "2026-10-19T12:00:00.000Z",
123
+ "platform": "android",
124
+ "channel": "production",
125
+ "runtimeVersion": "1.0.0",
126
+ "updateId": null,
127
+ "nativeVersion": "1.0.0",
128
+ "nativeBuild": "1",
129
+ "isEmbeddedLaunch": true,
130
+ "isEmergencyLaunch": false
131
+ }
132
+ ```
133
+
134
+ Responses return `status: accepted | duplicate | stale`. A reused sequence with a
135
+ different event ID is 409; malformed input is 400, oversized input 413, unsupported
136
+ content type 415, unavailable storage 503. Sequence is a positive safe integer.
137
+ Only accepted events refresh `last_seen_at`; client time is diagnostic, not the
138
+ basis for activity windows. An offline event's receipt does not prove the device
139
+ is still online. Daily activity is derived from server receipts after analytics
140
+ collection begins; it does not reconstruct offline usage or historic DAU.
141
+
142
+ The durable AsyncStorage envelope contains identity, sequence and a one-event
143
+ outbox. Startup and active foreground report the launched version; foreground
144
+ retries use a capped backoff and an 8-second request timeout. Pending snapshots
145
+ may be coalesced, so offline transitions are not an exhaustive audit log. Database
146
+ state and observed version transitions commit atomically. Epoch changes pointing
147
+ to the same artifact do not create fake version transitions. Resolved snapshots
148
+ survive deletion of the artifact for a device still reporting that launch ID.
149
+
150
+ The generated `useOtaUpdates(options)` hook exposes shared candidate/download state,
151
+ `check()`, `download()`, `reload()`, `retry()` and store upgrade handling. Identity is
152
+ persisted and the `installation_id` and `device_id` Expo extra parameters are set before
153
+ checks/downloads. Root options configure automatic checks, downloads and reloads;
154
+ server delivery/guard policy controls background and required updates. See the
155
+ [client lifecycle guide](./ota-client-lifecycle.md) for the complete contract.
156
+
157
+ The compatibility exports `getInstallationId()`, `getDeviceId()`,
158
+ `checkForUpdateAsync()` and `fetchUpdateAsync()` remain available. Low-level check/fetch
159
+ wrappers wait for identity but do not apply hook policies. Direct Expo checks at module
160
+ initialization are not intercepted. Do not mix those calls with hook orchestration.
161
+ The configured native automatic check is `NEVER`; the hook performs checks after
162
+ initialization. Dev/Expo Go/web builds do not report.
163
+
164
+ A heartbeat describes the running bundle, never a checked or merely downloaded candidate.
165
+ For an OTA served through an emergency redirect, its signed `manifest.metadata.channel`
166
+ is the reported channel; embedded launches use the configured channel. Resolver scope
167
+ checks remain strict. A failed telemetry request does not block checks or app launch.
168
+
169
+ ## Scope and access
170
+
171
+ An installation ID is not a physical device identifier or user ID. App data
172
+ clearing/reinstallation may create a new ID; OS backup/restore may copy local
173
+ storage. Accounts are outside this feature. A separate app/server-scoped Device ID supports
174
+ reinstall-resistant targeting; it does not merge installations or identify a person.
175
+ Heartbeat is self-reported, unauthenticated telemetry, not an authorization or
176
+ health attestation. It contains no admin/database/S3 token. Protect the public
177
+ endpoint with deployment-level request limits appropriate to your traffic; forged
178
+ clients can submit telemetry. Do not use this registry alone to grant secrets.
179
+
180
+ Reports require an admin session (admin/operator/viewer); publisher access tokens
181
+ cannot list installation IDs. RPC/table access is revoked from PUBLIC, anon and
182
+ authenticated roles; the server uses the table owner or Supabase service_role.
183
+ If you use a separate PostgreSQL runtime role, grant it the necessary table,
184
+ sequence and function privileges and configure RLS policies deliberately.
185
+
186
+ [Device audiences](./device-targeting.md) support smoke-only delivery to selected
187
+ Device IDs or Installation IDs and widening the same release to everyone. This is
188
+ release targeting, not a general feature flag rule engine.
189
+
190
+ ## Regression checks
191
+
192
+ ```sh
193
+ npm test
194
+ npx tsc --noEmit
195
+ npm run build
196
+ # Disposable database only, after applying migrations:
197
+ export OTA_TEST_DATABASE_URL=postgresql://...
198
+ node scripts/tests/device-heartbeat.mjs
199
+ # Fresh disposable database with schema.sql applied:
200
+ export OTA_TEST_DATABASE_URL=postgresql://...
201
+ node scripts/tests/device-analytics.mjs
202
+ # Empty disposable database: upgrade path, then the analytics regressions above:
203
+ export OTA_TEST_DATABASE_URL=postgresql://...
204
+ node scripts/tests/device-analytics-migrations.mjs
205
+ # A separate empty disposable database: fresh canonical schema path:
206
+ export OTA_TEST_DATABASE_URL=postgresql://...
207
+ node scripts/tests/device-analytics-migrations.mjs --fresh
208
+ ```
209
+
210
+ The database check covers unknown/resolved/embedded launches, duplicates, stale
211
+ requests, sequence conflicts, same-artifact epoch rotation, artifact deletion,
212
+ scoped/freshness statistics, and simultaneous first registration. Client tests
213
+ cover durable retries, storage failures, concurrent observations and stale acks.
214
+
215
+ Analytics checks cover daily deduplication and concurrent writes, snapshot versus
216
+ entry-state segmentation, filters and pagination-independent aggregates, missing
217
+ history versus zero activity, retention maturity, and 90-day cleanup. Migration
218
+ checks verify existing rows remain unchanged, no history is fabricated, and
219
+ reapplying a migration preserves collection start. They use only the explicitly
220
+ provided `OTA_TEST_DATABASE_URL`; they never load `.env` or `.env.local`. The
221
+ migration runner requires an empty disposable database owned by its connection
222
+ role and leaves its schema installed for inspection. Analytics tests temporarily
223
+ adjust collection metadata and exercise cleanup; never run them on a live database.
224
+
225
+ ## Версии на графике
226
+
227
+ График разделён на runtime, канал и платформу. Доля каждой OTA считается внутри этого блока, а не от всех каналов сразу. `appVersion` извлекается из опубликованного manifest (`extra.expoClient.version`, затем `expoClient.version`); message остаётся комментарием и не используется как название версии. Рядом показан OTA ID, чтобы различать публикации с одинаковым `appVersion`. Если метаданные OTA недоступны, интерфейс явно показывает «Версия не указана», не подменяя её native-версией.
228
+
229
+ Одна OTA на нескольких native-сборках объединяется в одну полосу; исходные строки остаются в таблице «Все версии». Для существующей базы после миграции аналитики примените `docs/migrations/2026-10-22-device-version-metadata.sql`. Новая база получает изменение из `schema.sql`. Миграция не меняет установленные версии и политику доставки.
230
+
231
+ ## Device targeting
232
+
233
+ See [Device-targeted releases](./device-targeting.md) for the separate reinstall-resistant Device ID, automatic configurator integration and smoke-test rollout workflow. Installation analytics still count installations, not deduplicated physical phones.
@@ -0,0 +1,89 @@
1
+ -- Stable manifest identity: publication epochs and immutable ID mappings.
2
+ begin;
3
+
4
+ create or replace function public.ota_channels_rotate_served_manifest_id()
5
+ returns trigger
6
+ language plpgsql
7
+ as $$
8
+ begin
9
+ if (
10
+ old.latest_update_id is distinct from new.latest_update_id
11
+ or old.active_update_id is distinct from new.active_update_id
12
+ or old.active_changed_at is distinct from new.active_changed_at
13
+ ) then
14
+ new.served_manifest_id := gen_random_uuid();
15
+ -- Expo compares timestamps at millisecond precision, including within
16
+ -- one transaction. now() alone can produce equal publication times.
17
+ new.served_manifest_changed_at := greatest(
18
+ clock_timestamp(),
19
+ old.served_manifest_changed_at + interval '1 millisecond',
20
+ old.active_changed_at + interval '1 millisecond',
21
+ new.active_changed_at
22
+ );
23
+ end if;
24
+ return new;
25
+ end;
26
+ $$;
27
+
28
+ create or replace function public.ota_updates_rotate_channel_on_activation()
29
+ returns trigger
30
+ language plpgsql
31
+ as $$
32
+ begin
33
+ if not new.is_active then
34
+ return new;
35
+ end if;
36
+ if tg_op = 'UPDATE' then
37
+ if old.is_active then
38
+ return new;
39
+ end if;
40
+ end if;
41
+
42
+ -- latest_update_id may already point at this previously inactive draft.
43
+ -- Activating it must still advance the epoch and the manifest timestamp.
44
+ update public.ota_update_channels
45
+ set served_manifest_id = gen_random_uuid(),
46
+ served_manifest_changed_at = greatest(
47
+ clock_timestamp(),
48
+ served_manifest_changed_at + interval '1 millisecond',
49
+ active_changed_at + interval '1 millisecond'
50
+ )
51
+ where runtime_version = new.runtime_version
52
+ and channel = new.channel
53
+ and platform = new.platform;
54
+ return new;
55
+ end;
56
+ $$;
57
+
58
+ drop trigger if exists trg_ota_updates_rotate_channel_on_activation
59
+ on public.ota_updates;
60
+ create trigger trg_ota_updates_rotate_channel_on_activation
61
+ after insert or update of is_active on public.ota_updates
62
+ for each row execute function public.ota_updates_rotate_channel_on_activation();
63
+
64
+ create or replace function public.ota_served_manifest_preserve_identity()
65
+ returns trigger
66
+ language plpgsql
67
+ as $$
68
+ begin
69
+ if old.served_manifest_id is distinct from new.served_manifest_id
70
+ or old.update_id is distinct from new.update_id
71
+ or old.runtime_version is distinct from new.runtime_version
72
+ or old.channel is distinct from new.channel
73
+ or old.platform is distinct from new.platform then
74
+ raise exception 'OTA_MANIFEST_IDENTITY_CONFLICT: served manifest identity cannot be reassigned'
75
+ using errcode = '23514';
76
+ end if;
77
+ -- Repeated manifest checks must not change the first-recorded timestamp.
78
+ new.created_at := old.created_at;
79
+ return new;
80
+ end;
81
+ $$;
82
+
83
+ drop trigger if exists trg_ota_served_manifest_preserve_identity
84
+ on public.ota_served_manifest_log;
85
+ create trigger trg_ota_served_manifest_preserve_identity
86
+ before update on public.ota_served_manifest_log
87
+ for each row execute function public.ota_served_manifest_preserve_identity();
88
+
89
+ commit;
@@ -0,0 +1,131 @@
1
+ -- Apply after schema.sql (including manifest identity). Safe to reapply.
2
+ begin;
3
+ alter table public.ota_device_state
4
+ add column if not exists reported_update_id uuid,
5
+ add column if not exists resolved_update_id uuid,
6
+ add column if not exists update_label text,
7
+ add column if not exists launch_kind text not null default 'unknown' check (launch_kind in ('embedded','ota','unknown')),
8
+ add column if not exists native_version text,
9
+ add column if not exists native_build text,
10
+ add column if not exists emergency_launch boolean not null default false,
11
+ add column if not exists observed_at timestamptz,
12
+ add column if not exists last_event_id uuid,
13
+ add column if not exists last_sequence bigint not null default 0 check (last_sequence between 0 and 9007199254740991);
14
+ alter table public.ota_device_transitions
15
+ add column if not exists event_id uuid,
16
+ add column if not exists before_state jsonb,
17
+ add column if not exists after_state jsonb;
18
+ create index if not exists idx_ota_device_state_seen on public.ota_device_state(last_seen_at desc, installation_id, platform);
19
+
20
+ -- Invoker privileges only; the application backend is the sole database caller.
21
+ create or replace function public.ota_record_heartbeat(p_event jsonb)
22
+ returns table(result text) language plpgsql set search_path = public as $$
23
+ declare
24
+ previous public.ota_device_state%rowtype;
25
+ artifact uuid;
26
+ label text;
27
+ kind text;
28
+ before_version jsonb;
29
+ after_version jsonb;
30
+ seq bigint := (p_event->>'sequence')::bigint;
31
+ reported uuid := (p_event->>'updateId')::uuid;
32
+ receipt timestamptz;
33
+ begin
34
+ if seq < 1 or seq > 9007199254740991 then raise exception 'INVALID_SEQUENCE'; end if;
35
+ insert into public.ota_device_state(installation_id,platform,runtime_version,channel)
36
+ values(p_event->>'installationId',p_event->>'platform',p_event->>'runtimeVersion',p_event->>'channel')
37
+ on conflict (installation_id,platform) do nothing;
38
+ select * into strict previous from public.ota_device_state
39
+ where installation_id=p_event->>'installationId' and platform=p_event->>'platform' for update;
40
+ if seq < previous.last_sequence then return query select 'stale'::text; return; end if;
41
+ if seq = previous.last_sequence then
42
+ if previous.last_event_id = (p_event->>'eventId')::uuid then
43
+ return query select 'duplicate'::text; return;
44
+ end if;
45
+ raise exception 'HEARTBEAT_SEQUENCE_CONFLICT';
46
+ end if;
47
+ receipt := greatest(previous.last_seen_at, clock_timestamp());
48
+ kind := case when (p_event->>'isEmbeddedLaunch')::boolean then 'embedded' else 'unknown' end;
49
+ if kind <> 'embedded' and reported is not null then
50
+ select u.update_id,u.comment into artifact,label from public.ota_updates u
51
+ where u.runtime_version=p_event->>'runtimeVersion' and u.channel=p_event->>'channel' and u.platform=p_event->>'platform'
52
+ and (u.update_id=reported or exists(select 1 from public.ota_served_manifest_log m
53
+ where m.served_manifest_id=reported and m.update_id=u.update_id and m.runtime_version=u.runtime_version
54
+ and m.channel=u.channel and m.platform=u.platform))
55
+ order by (u.update_id=reported) asc limit 1;
56
+ if artifact is null and previous.launch_kind='ota' and previous.reported_update_id=reported
57
+ and previous.runtime_version=p_event->>'runtimeVersion' and previous.channel=p_event->>'channel' then
58
+ artifact := previous.resolved_update_id; label := previous.update_label;
59
+ end if;
60
+ if artifact is not null then kind := 'ota'; end if;
61
+ end if;
62
+ before_version := jsonb_build_object('runtime',previous.runtime_version,'channel',previous.channel,
63
+ 'nativeVersion',previous.native_version,'nativeBuild',previous.native_build,'kind',previous.launch_kind,
64
+ 'updateId',coalesce(previous.resolved_update_id,previous.reported_update_id));
65
+ after_version := jsonb_build_object('runtime',p_event->>'runtimeVersion','channel',p_event->>'channel',
66
+ 'nativeVersion',p_event->>'nativeVersion','nativeBuild',p_event->>'nativeBuild','kind',kind,
67
+ 'updateId',coalesce(artifact,reported));
68
+ update public.ota_device_state set
69
+ runtime_version=p_event->>'runtimeVersion',channel=p_event->>'channel',
70
+ embedded_update_id=case when kind='embedded' then reported else previous.embedded_update_id end,
71
+ current_update_id=(select update_id from public.ota_updates where update_id=artifact),
72
+ served_manifest_id=case when kind<>'embedded' then reported end,
73
+ reported_update_id=reported,resolved_update_id=artifact,update_label=label,launch_kind=kind,
74
+ native_version=p_event->>'nativeVersion',native_build=p_event->>'nativeBuild',
75
+ emergency_launch=(p_event->>'isEmergencyLaunch')::boolean,observed_at=(p_event->>'observedAt')::timestamptz,
76
+ last_event_id=(p_event->>'eventId')::uuid,last_sequence=seq,last_seen_at=receipt
77
+ where installation_id=previous.installation_id and platform=previous.platform;
78
+ if previous.last_sequence=0 or before_version is distinct from after_version then
79
+ insert into public.ota_device_transitions(installation_id,platform,from_runtime,from_update_id,to_runtime,to_update_id,
80
+ transition_type,occurred_at,event_id,before_state,after_state)
81
+ values(previous.installation_id,previous.platform,case when previous.last_sequence>0 then previous.runtime_version end,
82
+ previous.resolved_update_id,p_event->>'runtimeVersion',artifact,
83
+ case when previous.last_sequence=0 then 'first_seen' else 'version_changed' end,receipt,
84
+ (p_event->>'eventId')::uuid,case when previous.last_sequence>0 then before_version end,after_version);
85
+ end if;
86
+ return query select 'accepted'::text;
87
+ end $$;
88
+
89
+ -- One statement gives the page and version distribution the same database snapshot.
90
+ create or replace function public.ota_devices_report(p_days integer default 7, p_platform text default null,
91
+ p_channel text default null, p_runtime text default null, p_offset integer default 0)
92
+ returns table(report jsonb) language sql stable set search_path=public as $$
93
+ with filtered as (
94
+ select * from public.ota_device_state where last_sequence>0
95
+ and last_seen_at >= now() - make_interval(days => p_days)
96
+ and (p_platform is null or platform=p_platform)
97
+ and (p_channel is null or channel=p_channel)
98
+ and (p_runtime is null or runtime_version=p_runtime)
99
+ ), versions as (
100
+ select platform,channel,runtime_version,native_version,native_build,launch_kind,
101
+ coalesce(resolved_update_id,reported_update_id) as update_id,max(update_label) as update_label,count(*) as installations
102
+ from filtered group by platform,channel,runtime_version,native_version,native_build,launch_kind,
103
+ coalesce(resolved_update_id,reported_update_id)
104
+ ), page as (select * from filtered order by last_seen_at desc,installation_id,platform limit 50 offset p_offset)
105
+ select jsonb_build_object('total',(select count(*) from filtered),'pageSize',50,
106
+ 'devices',coalesce((select jsonb_agg(to_jsonb(page) order by last_seen_at desc,installation_id,platform) from page),'[]'::jsonb),
107
+ 'versions',coalesce((select jsonb_agg(to_jsonb(versions) order by installations desc,platform,channel,runtime_version,update_id) from versions),'[]'::jsonb));
108
+ $$;
109
+
110
+ alter table public.ota_device_state enable row level security;
111
+ alter table public.ota_device_transitions enable row level security;
112
+ revoke all on public.ota_device_state, public.ota_device_transitions from public;
113
+ revoke all on function public.ota_record_heartbeat(jsonb) from public;
114
+ revoke all on function public.ota_devices_report(integer,text,text,text,integer) from public;
115
+ do $$ declare role_name text; begin
116
+ foreach role_name in array array['anon','authenticated'] loop
117
+ if exists(select 1 from pg_roles where rolname=role_name) then
118
+ execute format('revoke all on public.ota_device_state, public.ota_device_transitions from %I',role_name);
119
+ execute format('revoke all on sequence public.ota_device_transitions_id_seq from %I',role_name);
120
+ execute format('revoke all on function public.ota_record_heartbeat(jsonb) from %I',role_name);
121
+ execute format('revoke all on function public.ota_devices_report(integer,text,text,text,integer) from %I',role_name);
122
+ end if;
123
+ end loop;
124
+ if exists(select 1 from pg_roles where rolname='service_role') then
125
+ grant select,insert,update on public.ota_device_state, public.ota_device_transitions to service_role;
126
+ grant usage,select on sequence public.ota_device_transitions_id_seq to service_role;
127
+ grant execute on function public.ota_record_heartbeat(jsonb) to service_role;
128
+ grant execute on function public.ota_devices_report(integer,text,text,text,integer) to service_role;
129
+ end if;
130
+ end $$;
131
+ commit;