#import "keys" #import "byte_text_linux" #import "drawing_props" #import, file "storage_test_support.zi"; #import, file "../src/app/text_buffers.zi"; #import, file "../src/storage/data.zi"; #import, file "../src/storage/state.zi"; #import, file "../src/storage/db.zi"; #import, file "../src/storage/session_mood.zi"; #import, file "../src/storage/storage_core.zi"; #import, file "../src/storage/sync_state.zi"; #import, file "../src/storage/storage_settings.zi"; #import, file "../src/storage/storage_json_sql.zi"; #import, file "../src/storage/storage_sessions.zi"; #import, file "../src/storage/storage_elist.zi"; #import, file "../src/storage/sync_review.zi"; #import, file "../src/storage/import.zi"; #import, file "../src/storage/sync_account.zi"; #import, file "../src/storage/sync_account_host.zi"; #import, file "../src/storage/sync_runtime.zi"; #import, file "../src/storage/account_types.zi"; #import, file "../src/screens/elist_types.zi"; #import, file "../src/habits/habit_types.zi"; #import, file "../src/habits/habit_memory.zi"; #import, file "../src/storage/storage_habits.zi"; #import, file "../src/habits/habit_model.zi"; #import, file "../src/app/account_activity_model.zi"; #import, file "../src/storage/bundled_app_records.zi"; #import "text_buffer" #import "wire" #import "authorization" #import, file "../src/core/types.zi"; #import, file "../src/apps/package_files.zi"; #import, file "../src/apps/diary_store.zi"; #import, file "../src/apps/diary_records.zi"; #import, file "../src/apps/diary_blobs_native.zi"; #import, file "../src/apps/diary_blobs.zi"; #import, file "../src/apps/media_store.zi"; #import, file "../src/apps/media_diary_photos.zi"; #import, file "../src/apps/entity_photos.zi"; #import, file "../src/storage/entity_records.zi"; #import, file "../src/storage/sync_record_crypto.zi"; #import "crypto" #import "json_scan" #import, file "../src/storage/sync_nodes.zi"; #import, file "../src/storage/sync_node_storage.zi"; #import, file "../src/storage/media_node_session.zi"; #import, file "../src/storage/sync_session.zi"; #import, file "../src/storage/sync_page_store.zi"; #import "sync_flow" #import "c_string" #import "auth" #import "file_linux" // Two clients, a friend, and fresh installs syncing through a real Mesh // server (with a proxy that drops one response), from the first upload to // backup restore and deletion. The runner passes the server address in // SYNC_TEST_URL and the faulty proxy's in SYNC_TEST_FAULT_URL, and points // APP_DATA_ROOT at a disposable directory. c :: #system_library "c"; // Older key files, opened the way Entity's import reads them. read_key_file :: (account: *AccountKeys, path: *u8) -> s32 { account.* = AccountKeys.{} body := host_load_file_text(path) if body == null { return 0 } result := ParseAccountKeys(TextFromCString(body), account) host_unload_file_text(body) return result } get_environment :: (name: *u8) -> *u8 #foreign c "getenv"; pause_microseconds :: (microseconds: u32) -> s32 #foreign c "usleep"; habits_a: Habits; elists: EListState; requests_text: [8192]u8; friends_text: [8192]u8; environment_text :: (name: string) -> string { buffer: TextBuffer append(*buffer, name) value := get_environment(*buffer.bytes[0]) if value == null { return "" } return TextFromCString(value) } AlbumHabitId :: () -> string { return "00000000-0000-4000-8000-000000000042" } open_client :: (root: string) { storage_close() check_true("open client storage", storage_init(root) != 0) } expect_habit :: (id: string, name: string, date: s32) { habits_a = Habits.{} check_true("load habits", storage_habits_load(cast(*void)*habits_a) != 0) found: *Habit = null index: s32 = 0 while index < habits_a.count { if TextFromCString(*habits_a.items[index].id[0]) == id { found = *habits_a.items[index] } index += 1 } check_true(join("habit exists: ", id), found != null) if found != null { check_true("habit name", TextFromCString(*found.name[0]) == name) check_int("habit has one day", found.day_count, 1) if found.day_count > 0 { check_int("habit day date", found.days[0].day_index, date) check_true("habit day completed", found.days[0].completed != 0) check_int("habit day count", found.days[0].count, 1) } } habits_free(*habits_a) } seed_default_habits :: () { habits_a = Habits.{} habits_a.count = 2 unused AppCopyText("meditation", habits_a.items[0].id[:]) unused AppCopyText("Meditation", habits_a.items[0].name[:]) unused AppCopyText("yoga", habits_a.items[1].id[:]) unused AppCopyText("Yoga", habits_a.items[1].name[:]) index: s32 = 0 while index < 2 { habits_a.items[index].color = Color.{126, 183, 230, 255} habits_a.items[index].counter_target = 1 habits_a.items[index].reminder_hour = -1 index += 1 } storage_habits_save(cast(*void)*habits_a) check_int("defaults seeded", storage_habit_count(), 2) habits_free(*habits_a) } expect_list :: (list_id: string, item_id: string, title: string, comment: string, done: s32) { elist_reset(*elists, 0) check_true("load lists", storage_elist_load(cast(*void)*elists) != 0) lists: s32 = 0 items: s32 = 0 storage_elist_counts(*lists, *items) check_true("lists and items exist", lists > 0 && items > 0) found_list: bool = false found_item: bool = false index: s32 = 0 while index < elists.list_count { if TextFromCString(*elists.lists[index].id[0]) == list_id && TextFromCString(*elists.lists[index].title[0]) == title { found_list = true } index += 1 } index = 0 while index < elists.item_count { if TextFromCString(*elists.items[index].id[0]) == item_id && TextFromCString(*elists.items[index].list_id[0]) == list_id && TextFromCString(*elists.items[index].comment[0]) == comment && elists.items[index].done == done { found_item = true } index += 1 } check_true(join("list ", title), found_list) check_true(join("item in ", title), found_item) } // Syncs until nothing is left queued, retrying transient failures. synchronize :: (url: string) { check_true("select the sync node", SyncNodeActivate(url)) storage_set_sync_enabled(1) attempt: s32 = 0 while attempt < 8 { result: s32 = SyncStoredAccount(url) if result != 0 { check_int("sync attempt result", result, 0) unused pause_microseconds(2000000) attempt += 1 continue } if storage_sync_review_pending() != 0 { check_true("apply remote when local is empty", storage_sync_review_apply_remote_if_local_empty() != 0) check_true("review cleared", storage_sync_review_pending() == 0) } status: StorageSyncStatus check_true("status", storage_sync_status(*status) != 0) if status.queued_changes == 0 { return } attempt += 1 } check_true("sync drained the queued changes", false) } // The node's file for a blob of `app` under the server's data directory. server_app_blob_size :: (server: string, app: string, blob: string) -> s32 { path: TextBuffer append(*path, data_root()) append(*path, server) append(*path, "server.db.blobs/") append(*path, storage_get_setting_text("sync_public_id")) append(*path, "/") append(*path, app) append(*path, "/") append(*path, blob) return cast(s32)PackageFileSize(TextFromCString(*path.bytes[0])) } // The node's file for a sealed chunk of the account's entity data. server_blob_size :: (server: string, blob: string) -> s32 { return server_app_blob_size(server, "entity", blob) } // The address of the photo's chunk, or of its preview's. library_record_blob :: (hash: string, preview: bool, output: []u8) -> string { record := MediaEntityRecord(hash) content := ifx preview then EntityPreviewContent(record) else EntityPhotoContent(record) PackageFree(record) output[0] = cast(u8)0 if content.chunk_count == 1 { unused AppCopyText(TextUntilNul(content.chunks[0].address[:]), output) } return TextUntilNul(output) } // A photo's bytes: PNG's signature, then a pattern of `seed`. server_photo :: (bytes: []u8, seed: s32) -> string { header: [8]u8 = .[cast(u8)137, cast(u8)80, cast(u8)78, cast(u8)71, cast(u8)13, cast(u8)10, cast(u8)26, cast(u8)10] for index: cast(s32)0..cast(s32)bytes.count - 1 { bytes[index] = ifx index < 8 then header[index] else cast(u8)((index * 13 + seed) % 251) } return TextFromBytes(bytes) } server_photo_file :: (name: string, image: string) -> string { source: TextBuffer append(*source, data_root()) append(*source, "/") append(*source, name) path := PackageText(TextFromCString(*source.bytes[0]), "") unused RemoveFile(path) file := OpenExclusivePrivate(path) written := file.valid && WriteTextAt(file, image, 0) == image.count check_true("write the photo to add", CloseFile(file) && written) return path } server_move_steps :: () { MediaDiaryPhotosDue() for step: 0..80 { unused step unused MediaDiaryPhotosStep() } } // A photo travels as the account's entity data: its record in the // account's own signed sync, its bytes as one sealed chunk, which the node // keeps at the photo's size plus 16 bytes. The account's other device gets // the record in its normal sync and opens the photo whole. expect_photo_copy :: (url: string, a: string, b: string) { open_client(a) png: [6000]u8 image := server_photo(png[:], 7) source_path := server_photo_file("photo-source.png", image) added := MediaImportFile(source_path) check_true("add the photo", added.succeeded) hash := PackageText(TextFromBytes(added.hash[:64]), "") synchronize(url) DiaryBlobsSendNative(url) record := MediaEntityRecord(hash) content := EntityPhotoContent(record) PackageFree(record) check_true("the photo's chunk is on the node", content.chunk_count == 1) synchronize(url) check_int("the node keeps the photo's size plus 16 bytes", server_blob_size("/", TextUntilNul(content.chunks[0].address[:])), 6016) open_client(b) synchronize(url) item := MediaRead(hash) check_true("the other device has the photo's record from its sync", item.valid && item.entity) check_true("its original waits there", PackageFileSize(MediaPath(hash, false)) != image.count) MediaWant(hash) DiaryBlobsSendNative(url) check_true("the photo arrives whole on the other device", PackageRead(MediaPath(hash, false), DIARY_FILE_LIMIT) == image) PackageFree(hash) PackageFree(source_path) } // A photo a released version kept as an old copy at /api/v1/blobs/inbe/ // moves on a real node: its old copy comes to this device, its chunks go // to the node, the node confirms them, they come back whole, and only then // does the node delete the old copy. expect_old_copy_moves :: (url: string, a: string) { open_client(a) png: [7000]u8 image := server_photo(png[:], 29) descriptor := cast(*TextDescriptor)(*image) hash_bytes: [65]u8 storage_sha256_hex(descriptor.data, image.count, *hash_bytes[0]) hash := PackageText(TextFromCString(*hash_bytes[0]), "") // Sealed as released versions sealed it. master: [32]u8 check_true("the account key makes old copies", storage_private_record_key_for_context("inbe-diary-blob-key-v1", *master[0]) != 0) file_key: [32]u8 check_true("the file's key", HmacSha256Text(*master[0], 32, hash, *file_key[0]) != 0) sealed: [7016]u8 nonce: [12]u8 aad := "inbe.diary.blob.v1" aad_bytes := cast(*TextDescriptor)(*aad) check_true("seal the old copy", ChaCha20Poly1305Seal(*file_key[0], *nonce[0], descriptor.data, image.count, aad_bytes.data, aad.count, *sealed[0], 7016) != 0) address_bytes: [65]u8 storage_sha256_hex(*sealed[0], 7016, *address_bytes[0]) address := TextFromCString(*address_bytes[0]) key_hex: [65]u8 unused BytesToHex(*file_key[0], 32, *key_hex[0], 65) old_path := PackageText("/api/v1/blobs/inbe/", address) answer: [64]u8 status: s32 = 0 length: s64 = 0 check_int("a released version puts its old copy on the node", SendStoredBlob(url, "PUT", old_path, TextFromBytes(sealed[:]), answer[:], *status, *length), 0) check_int("the node keeps it", status, 204) check_int("at the photo's size plus 16 bytes", server_app_blob_size("/", "inbe", address), 7016) old_out: Vec(u8) BuilderPrint(*old_out, "{\"hash\":\"%\",\"size\":7000,\"type\":\"png\",\"name\":\"Old.png\",", hash) BuilderPrint(*old_out, "\"day\":\"2024-05-01\",\"taken\":\"2024-05-01\",\"added\":1792000000,\"capture\":0,") BuilderPrint(*old_out, "\"trashed\":0,\"blob\":\"%\",\"key\":\"%\"}", address, TextFromCString(*key_hex[0])) old_record := BuilderFinish(old_out) old_key := PackageText("cell.media.", hash) storage_set_setting_text(old_key, old_record) server_move_steps() check_true("without its bytes the photo waits", !MediaRead(hash).entity) DiaryBlobsSendNative(url) check_true("its old copy comes", PackageRead(MediaPath(hash, false), DIARY_FILE_LIMIT) == image) server_move_steps() check_true("then it moves", MediaRead(hash).entity) synchronize(url) DiaryBlobsSendNative(url) synchronize(url) check_int("the old copy stays until the photo comes back whole", server_app_blob_size("/", "inbe", address), 7016) DiaryBlobsSendNative(url) server_move_steps() check_true("its old record names the photo", FieldAt(storage_get_setting_text(old_key), 0, "photo") >= 0) synchronize(url) DiaryBlobsSendNative(url) check_true("the node deleted the old copy", server_app_blob_size("/", "inbe", address) <= 0) record := MediaEntityRecord(hash) content := EntityPhotoContent(record) PackageFree(record) check_int("the node keeps the photo's chunk", server_blob_size("/", TextUntilNul(content.chunks[0].address[:])), 7016) check_true("the old record keeps every field", FieldAt(storage_get_setting_text(old_key), 0, "blob") >= 0 && FieldAt(storage_get_setting_text(old_key), 0, "name") >= 0) SecureWipe(*master[0], 32) SecureWipe(*file_key[0], 32) PackageFree(old_key) PackageFree(old_record) PackageFree(old_path) PackageFree(hash) } // A photo added to the library on one device appears on the other with its // preview, and opens its original there. Copies go to every node whose // photo upload is on and not to one where it is off, each node on its own // session; downloads fall back from the sync node to the next. expect_library_copies :: (url: string, second: string, a: string, b: string) { open_client(a) check_true("a adds a second node", SyncNodeAdd(second)) check_true("a keeps photos off the sync node", SyncNodeSetMediaUpload(url, false)) check_true("photos go to the second node", SyncNodeMediaUpload(second)) jpeg: [9000]u8 for index: cast(s32)0..cast(s32)8999 { jpeg[index] = cast(u8)((index * 31 + 11) % 251) } jpeg[0] = cast(u8)255 jpeg[1] = cast(u8)216 jpeg[2] = cast(u8)255 jpeg[8998] = cast(u8)255 jpeg[8999] = cast(u8)217 image := TextFromBytes(jpeg[:]) source: TextBuffer append(*source, data_root()) append(*source, "/IMG_0042.jpg") source_path := TextFromCString(*source.bytes[0]) unused RemoveFile(source_path) file := OpenExclusivePrivate(source_path) written := file.valid && WriteTextAt(file, image, 0) == image.count check_true("write the photo to add", CloseFile(file) && written) added := MediaImportFile(source_path) check_true("a adds the photo to the library", added.succeeded) hash_bytes: [65]u8 unused AppCopyText(TextFromBytes(added.hash[:64]), hash_bytes[:]) hash := TextUntilNul(hash_bytes[:]) check_true("a made a preview", EntityPreviewContent(MediaEntityRecord(hash)).valid) synchronize(url) DiaryBlobsSendNative(url) original_blob: [65]u8 preview_blob: [65]u8 check_int("the original's chunk is named", cast(s32)library_record_blob(hash, false, original_blob[:]).count, 64) check_int("the preview's chunk is named", cast(s32)library_record_blob(hash, true, preview_blob[:]).count, 64) check_int("the second node keeps the original sealed", server_blob_size("/second/", TextUntilNul(original_blob[:])), 9016) check_true("the second node keeps the preview", server_blob_size("/second/", TextUntilNul(preview_blob[:])) > 16) check_true("the sync node, with photos off, keeps neither", server_blob_size("/", TextUntilNul(original_blob[:])) <= 0 && server_blob_size("/", TextUntilNul(preview_blob[:])) <= 0) pass: DiaryBlobPass check_true("nothing is sent twice", !DiaryBlobPlan(*pass, url)) // Each node has its own session, apart from the sync's. normalized: [256]u8 check_true("normalize the second node", SyncNodeAddress(second, normalized[:])) media_session: Session MediaSessionLoad(TextUntilNul(normalized[:]), *media_session, 1) check_true("the second node has a media session", media_session.token[0] != cast(u8)0) check_true("it is not the sync's session", TextUntilNul(media_session.token[:]) != storage_get_setting_text("sync_auth_token")) synchronize(url) open_client(b) check_true("b adds the second node", SyncNodeAdd(second)) synchronize(url) // The photo of the photo check is there too. check_int("the photo is in b's library", MediaQuery("", false), 2) check_true("its preview waits on b", MediaAsset(hash, false) == "") DiaryBlobsSendNative(url) preview_asset := PackageText(MediaAsset(hash, false), "") check_true("the preview arrives from the second node", preview_asset.count > 0 && preview_asset[:14] == "media/preview/") check_true("the preview's bytes are whole", MediaAssetView(preview_asset).found) check_true("opening the photo shows the preview first", MediaAsset(hash, true) == preview_asset) DiaryBlobsSendNative(url) original_asset := MediaAsset(hash, true) check_true("the original arrives once opened", original_asset.count > 0 && original_asset[:14] != "media/preview/") check_true("the original opens whole", MediaAssetView(original_asset).data == image) PackageFree(preview_asset) // Turning photos on for the sync node sends it the copies it lacks. open_client(a) check_true("a turns photos on for the sync node", SyncNodeSetMediaUpload(url, true)) DiaryBlobsSendNative(url) check_int("the sync node now keeps the original", server_blob_size("/", TextUntilNul(original_blob[:])), 9016) check_true("and the preview", server_blob_size("/", TextUntilNul(preview_blob[:])) > 16) check_true("still nothing is sent twice", !DiaryBlobPlan(*pass, url)) MediaStoreClose() } mood_is :: (id: string, want: s32) -> bool { loaded: SessionMoodCheckin return storage_load_session_checkin(id, *loaded) != 0 && loaded.mood_after == want } #program_export Check :: () -> s32 { url := environment_text("SYNC_TEST_URL") fault := environment_text("SYNC_TEST_FAULT_URL") second_url := environment_text("SYNC_TEST_SECOND_URL") if url.count == 0 || fault.count == 0 || second_url.count == 0 { return 90 } guard := support_begin("/tmp/inbe-sync-server-") if guard != 0 { return guard } // Keep the URLs, which point into the environment, across storage calls. server: TextBuffer append(*server, url) proxy: TextBuffer append(*proxy, fault) second_server: TextBuffer append(*second_server, second_url) url = TextFromCString(*server.bytes[0]) fault = TextFromCString(*proxy.bytes[0]) second_url = TextFromCString(*second_server.bytes[0]) ask := SyncAccountLocalDataChoice.SYNC_ACCOUNT_LOCAL_DATA_ASK ok := SyncAccountSaveResult.SYNC_ACCOUNT_SAVE_OK a := make_root("a") b := make_root("b") restored := make_root("restored") friend_root := make_root("friend") defaults_root := make_root("restored_defaults") key_path: TextBuffer append(*key_path, data_root()) append(*key_path, "/account.key") backup: TextBuffer append(*backup, data_root()) append(*backup, "/backup.zip") alias: string = "restore_test" friend_alias: string = "friend_test" account: AccountKeys friend_account: AccountKeys restored_account: AccountKeys default_account: AccountKeys id: [256]u8 other_id: [256]u8 duration: [1]s32 = .[60] checkin: SessionMoodCheckin open_client(a) check_true("generate account", sync_account_generate(*account) != 0) check_true("save account", sync_account_save(*account, ask) == ok) storage_set_setting_int("habit_shop_borrow_limit", 75) habit_name: string = "Recovery meditation" habits_a = Habits.{} habits_a.count = 1 unused AppCopyText(AlbumHabitId(), habits_a.items[0].id[:]) unused AppCopyText(habit_name, habits_a.items[0].name[:]) habits_a.items[0].color = Color.{82, 119, 193, 255} habits_a.items[0].counter_target = 1 habits_a.items[0].reminder_hour = -1 storage_habits_save(cast(*void)*habits_a) habits_free(*habits_a) check_true("save habit day", storage_habit_day_save(AlbumHabitId(), 20260919, 1, 1) != 0) expect_habit(AlbumHabitId(), habit_name, 20260919) check_true("save session", storage_save_session_for_activity(*duration[0], 1, 0, 1, *id[0], 256) != 0) checkin.mood_after = 4 session := TextFromCString(*id[0]) check_true("save check-in", storage_save_session_checkin(session, *checkin) != 0) check_true("syncing offline fails", SyncStoredAccount("http://127.0.0.1:1") != 0) check_int("an offline failure keeps local work", storage_session_count(), 1) open_client(a) check_true("check-in survives the failure", mood_is(session, 4)) // The server commits the upload, but the proxy drops its response. // Mesh Client retries it without requiring another connect or sync. check_true("select interrupted transfer node", SyncNodeActivate(fault)) storage_set_sync_enabled(1) check_int("interrupted upload recovers automatically", SyncStoredAccount(fault), 0) open_client(a) synchronize(url) page_state := SyncPageState.{.enabled = true} check_true("enable bounded record sync", SaveStoredSyncPage(url, *page_state)) for idle: cast(s32)0..2 { unused idle check_int("unchanged paged sync succeeds", SyncStoredAccount(url), 0) } // A download that began at a lower position, as a repair from version // zero does, can leave its cursor behind this device's position. The // node refuses such a cursor; the next sync starts the download again. stale_page := SyncPageState.{.enabled = true, .pending = true} check_true("save a cursor behind the position", CopyCString("{\"version\":1,\"collection\":\"private.inbe.v1.habits\",\"id\":\"stale\"}", stale_page.cursor[:]) && SaveStoredSyncPage(url, *stale_page)) check_int("a cursor behind the position restarts the download", SyncStoredAccount(url), 0) check_true("the restarted download completes", LoadStoredSyncPage(url, *stale_page) && !stale_page.pending && stale_page.cursor[0] == cast(u8)0) storage_set_setting_text("sync_server_url", url) storage_set_sync_enabled(1) check_int("register alias", RegisterAliasStored(url, alias), 0) list_id: [37]u8 item_id: [37]u8 check_true("create list", storage_elist_create_list("Travel", *list_id[0]) != 0) list_text := TextFromCString(*list_id[0]) check_true("create item", storage_elist_create_item(list_text, "Pack bag", "Passport", *item_id[0]) != 0) item_text := TextFromCString(*item_id[0]) synchronize(url) open_client(b) check_true("second device joins", sync_account_save(*account, ask) == ok) synchronize(url) check_true("alias reaches the second device", storage_get_setting_text("sync_account_alias") == alias) check_int("session reaches the second device", storage_session_count(), 1) expect_habit(AlbumHabitId(), habit_name, 20260919) expect_list(list_text, item_text, "Travel", "Passport", 0) check_int("borrow allowance reaches the second device", storage_get_setting_int("habit_shop_borrow_limit", 0), 75) storage_set_setting_int("habit_shop_borrow_limit", 125) synchronize(url) // Private live activity uses the same authenticated, encrypted account // transport as Lumi history, without creating another completed result. open_client(a) live: AccountActivity synchronize(url) check_int("updated borrow allowance returns to the first device", storage_get_setting_int("habit_shop_borrow_limit", 0), 125) unused AppCopyText("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", live.session_id[:]) unused AppCopyText("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", live.device_id[:]) live.active = 1 live.screen = ScreenMeditation live.time = BundledAppRecordClock() / 1000000 live.revision = 1 live.duration = 600 live.remaining = 480 live.elapsed = 120 live_payload: [2048]u8 check_true("serialize running activity", ActivityWrite(live, live_payload[:])) check_true("queue private running activity", BundledAppRecordWrite(ActivityRecordKey, TextUntilNul(live_payload[:]))) synchronize(url) open_client(b) synchronize(url) observed: AccountActivity live_document := BundledAppRecordRead(ActivityRecordKey) check_true("same running activity reaches another device", ActivityRead(live_document, *observed) && observed.remaining == 480 && observed.active == 1 && TextUntilNul(observed.session_id[:]) == TextUntilNul(live.session_id[:])) PackageFree(live_document) command: [1024]u8 writer := Writer.{command[:], 0, true} writer = WriteText(writer, "{\"id\":\"cccccccccccccccccccccccccccccccc\",\"session_id\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"device_id\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"paused\":1,\"revision\":1,") writer = JsonNumberField(writer, "time", BundledAppRecordClock() / 1000000) writer = WriteByte(writer, cast(u8)125) check_true("queue private pause request", writer.valid && BundledAppRecordWrite(ActivityControlKey, TextUntilNul(command[:]))) synchronize(url) open_client(a) synchronize(url) requested: ActivityControl command_document := BundledAppRecordRead(ActivityControlKey) live.time = BundledAppRecordClock() / 1000000 check_true("pause request reaches originating session", ActivityControlRead(command_document, *requested) && ActivityControlMatches(requested, live, live.time)) PackageFree(command_document) live.paused = 1 live.revision = 2 live.control_id = requested.id check_true("serialize acknowledged pause", ActivityWrite(live, live_payload[:])) check_true("queue acknowledged pause", BundledAppRecordWrite(ActivityRecordKey, TextUntilNul(live_payload[:]))) synchronize(url) open_client(b) synchronize(url) live_document = BundledAppRecordRead(ActivityRecordKey) check_true("pause acknowledgement returns to observer", ActivityRead(live_document, *observed) && observed.paused == 1 && TextUntilNul(observed.control_id[:]) == TextUntilNul(requested.id[:])) PackageFree(live_document) open_client(a) live.active = 0 live.revision = 3 live.time = BundledAppRecordClock() / 1000000 check_true("serialize completed activity", ActivityWrite(live, live_payload[:])) check_true("queue completed activity", BundledAppRecordWrite(ActivityRecordKey, TextUntilNul(live_payload[:]))) synchronize(url) open_client(b) synchronize(url) live_document = BundledAppRecordRead(ActivityRecordKey) check_true("completion reaches other device", ActivityRead(live_document, *observed) && observed.active == 0) PackageFree(live_document) check_int("live activity does not duplicate results", storage_session_count(), 1) expect_photo_copy(url, a, b) expect_library_copies(url, second_url, a, b) expect_old_copy_moves(url, a) open_client(b) check_true("complete the item", storage_elist_update_item(item_text, "Pack bag", "Passport", 1, 0) != 0) synchronize(url) open_client(a) synchronize(url) expect_list(list_text, item_text, "Travel", "Passport", 1) open_client(b) check_true("b sees the check-in", mood_is(session, 4)) checkin.mood_after = 2 check_true("b edits the check-in", storage_save_session_checkin(session, *checkin) != 0) synchronize(url) open_client(a) synchronize(url) check_true("a sees the edit", mood_is(session, 2)) synchronize(url) check_int("retrying an acknowledged upload is idempotent", storage_session_count(), 1) // Both clients edit offline; a's second edit is newer. open_client(b) checkin.mood_after = 1 check_true("b offline edit", storage_save_session_checkin(session, *checkin) != 0) open_client(a) checkin.mood_after = 3 check_true("a first offline edit", storage_save_session_checkin(session, *checkin) != 0) checkin.mood_after = 4 check_true("a second offline edit", storage_save_session_checkin(session, *checkin) != 0) open_client(b) synchronize(url) open_client(a) synchronize(url) open_client(b) synchronize(url) check_true("the newer edit wins", mood_is(session, 4)) // A friend, then restoring the same key on fresh installs. // A key file as older versions saved it; these must keep opening. legacy_key: [ACCOUNT_EXPORT_TEXT_SIZE]u8 check_true("write an older unprotected key file", AccountKeysText(*account, *legacy_key[0], ACCOUNT_EXPORT_TEXT_SIZE) != 0 && host_save_file_data(*key_path.bytes[0], *legacy_key[0], cast(s32)TextFromCString(*legacy_key[0]).count)) storage_set_setting_text("sync_server_url", url) storage_set_sync_enabled(1) open_client(friend_root) check_true("generate the friend's account", sync_account_generate(*friend_account) != 0) check_true("save the friend's account", sync_account_save(*friend_account, ask) == ok) storage_set_setting_text("sync_server_url", url) storage_set_sync_enabled(1) synchronize(url) check_int("friend registers an alias", RegisterAliasStored(url, friend_alias), 0) check_int("friend sends a request", SendFriendRequestStored(url, TextFromCString(*account.public_id[0])), 0) open_client(b) check_int("b fetches requests", FetchFriendRequests(url, requests_text[:]), 0) request_id: [128]u8 check_true("request id", storage_json_array_object_text(TextFromCString(*requests_text[0]), "$.incoming", 0, "id", *request_id[0], 128) != 0) check_int("b accepts the request", AcceptFriendRequestStored(url, TextFromCString(*request_id[0])), 0) open_client(restored) check_true("read the key back", read_key_file(*restored_account, *key_path.bytes[0]) != 0) check_true("same account id", TextFromCString(*restored_account.public_id[0]) == TextFromCString(*account.public_id[0])) check_true("restore the key", sync_account_save(*restored_account, ask) == ok) storage_set_setting_text("sync_server_url", url) storage_set_sync_enabled(1) synchronize(url) check_true("alias restored", storage_get_setting_text("sync_account_alias") == alias) check_int("borrow allowance restores with the account", storage_get_setting_int("habit_shop_borrow_limit", 0), 125) check_int("friends fetch", FetchFriends(url, friends_text[:]), 0) check_true("friendship recovered", contains(TextFromCString(*friends_text[0]), TextFromCString(*friend_account.public_id[0]))) check_int("session restored", storage_session_count(), 1) check_true("check-in restored", mood_is(session, 4)) expect_habit(AlbumHabitId(), habit_name, 20260919) expect_list(list_text, item_text, "Travel", "Passport", 1) // A new install may seed the default habits before the key is restored. open_client(defaults_root) seed_default_habits() check_true("read the key for the new install", read_key_file(*default_account, *key_path.bytes[0]) != 0) check_true("restore on the new install", sync_account_save(*default_account, ask) == ok) storage_set_setting_text("sync_server_url", url) storage_set_sync_enabled(1) synchronize(url) check_true("alias on the new install", storage_get_setting_text("sync_account_alias") == alias) check_int("session on the new install", storage_session_count(), 1) expect_habit(AlbumHabitId(), habit_name, 20260919) expect_list(list_text, item_text, "Travel", "Passport", 1) check_int("friends on the new install", FetchFriends(url, friends_text[:]), 0) check_true("friendship on the new install", contains(TextFromCString(*friends_text[0]), TextFromCString(*friend_account.public_id[0]))) // Backup and restore. open_client(b) check_true("export a backup", storage_export_zip(TextFromCString(*backup.bytes[0])) != 0) open_client(restored) check_true("import the backup", storage_import_zip(TextFromCString(*backup.bytes[0])) != 0) check_int("backup session", storage_session_count(), 1) check_true("backup check-in", mood_is(session, 4)) // Deleting one session leaves the unrelated upload alone. open_client(b) duration[0] = 90 check_true("save another session", storage_save_session_for_activity(*duration[0], 1, 0, 1, *other_id[0], 256) != 0) check_true("delete the first session", storage_delete_session(session) != 0) synchronize(url) open_client(a) synchronize(url) check_int("deletion preserves the unrelated upload", storage_session_count(), 1) other := TextFromCString(*other_id[0]) loaded: SessionMoodCheckin check_true("the other session loads", storage_load_session_checkin(other, *loaded) != 0) check_true("delete the other session", storage_delete_session(other) != 0) synchronize(url) open_client(b) synchronize(url) check_int("both deletions reached the second device", storage_session_count(), 0) storage_close() return failures }