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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions browser/e2e/tests/apps.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,70 @@ test.describe('apps', () => {
});
});

test('a value an app removes is gone, for the app and on the server', async ({
page,
}) => {
await newApp(page);

// `resource.remove(p).save()` from inside the frame, then a fresh read —
// what an importing app does when a source clears a field.
await setAppSource(
page,
`export async function view({ root, store }) {
const NAME = 'https://atomicdata.dev/properties/name';
const DESCRIPTION = 'https://atomicdata.dev/properties/description';
const out = document.createElement('output');
root.append(out);
try {
const made = await store.newResource({
propVals: { [NAME]: 'Row', [DESCRIPTION]: 'Goes away' },
});
const row = await store.getResource(made.subject);
row.remove(DESCRIPTION);
await row.save();
const after = await store.getResource(made.subject);
out.dataset.subject = made.subject;
out.textContent = 'description: ' + String(after.get(DESCRIPTION));
} catch (e) {
out.textContent = 'error: ' + e.message;
}
}`,
);
await page.reload();

const app = page.frameLocator('iframe[title="App"]');
const out = app.locator('output');
await expect(out).toHaveText(/^(description|error): /, { timeout: 60_000 });
await expect(out).toHaveText('description: undefined');

// And the server's copy, fetched over HTTP rather than the WebSocket the
// host's refresh uses, so a stale page copy cannot pass for it.
const subject = (await out.getAttribute('data-subject'))!;
const onServer = await page.evaluate(async (s: string) => {
const store = (
window as unknown as {
store: {
fetchResourceFromServer(
s: string,
o: { noWebSocket: boolean; forceOverride: boolean },
): Promise<{ getPropVals(): Record<string, unknown> }>;
};
}
).store;
const resource = await store.fetchResourceFromServer(s, {
noWebSocket: true,
forceOverride: true,
});

return resource.getPropVals();
}, subject);

expect(onServer['https://atomicdata.dev/properties/name']).toBe('Row');
expect(
onServer['https://atomicdata.dev/properties/description'],
).toBeUndefined();
});

test('an app that breaks says so, and offers to have it fixed', async ({
page,
}) => {
Expand Down
37 changes: 37 additions & 0 deletions browser/lib/src/resource.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,43 @@ describe('resource.ts', () => {
expect(loaded.get(recommends)).toEqual(order);
});

/**
* A property removed elsewhere (another client, or the server writing for
* an app through `/app-write`) must stay removed when the full state
* replaces this copy. The replace path used to rebuild the doc from the
* snapshot and then "heal" it from the cache — which still held the
* pre-removal values — so the removed value came back as a local op.
*/
it('a replacing snapshot drops properties the source removed', async ({
expect,
}) => {
const name = core.properties.name;
const description = core.properties.description;
const subject = 'https://example.com/replace-removes';

const server = new Resource(subject);
await server.set(name, 'Row', false);
await server.set(description, 'Goes away', false);
const before = server.getLoroDoc()!.export({ mode: 'snapshot' });

const page = new Resource(subject);
page.importLoroUpdate(before, true);
expect(page.get(description)).toBe('Goes away');

// The removal happens elsewhere, on top of the same state.
server.getLoroDoc()!.getMap('properties').delete(description);
server.getLoroDoc()!.commit();
const after = server.getLoroDoc()!.export({ mode: 'snapshot' });

page.importLoroUpdate(after, true);

expect(page.get(name)).toBe('Row');
expect(page.get(description)).toBeUndefined();
expect(
page.getLoroDoc()!.getMap('properties').get(description),
).toBeUndefined();
});

/**
* Regression: drawing onto a canvas whose strokes were seeded in bulk via
* `set()` (template/demo content) threw "pushContainer is not a function"
Expand Down
10 changes: 10 additions & 0 deletions browser/lib/src/resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3807,6 +3807,16 @@ export class Resource<C extends OptionalClass = any> {
// Drop any seeded/partial state so the incoming snapshot is authoritative.
if (replace) {
this.resetLoroState();

// The cache holds the state being replaced, not values that arrived with
// these bytes. Left in place, `getLoroDoc()`'s heal pass writes every key
// the snapshot lacks back into the doc — so a property removed at the
// source came back as a local op (an app's `/app-write` remove seemed
// not to stick). Server-derived keys are not in Loro; keep those.
for (const key of Object.keys(this.#cache)) {
if (!isDerivedByServer(key)) delete this.#cache[key];
}

// Point `getLoroDoc()` at these bytes so it imports the snapshot
// instead of seeding a *new* LoroList per array from `#cache`.
// Seeding-then-merging was the OPFS cold-load flash: two concurrent
Expand Down
20 changes: 19 additions & 1 deletion lib/src/hierarchy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -464,13 +464,31 @@ fn check_rights_impl<'a, S: Storelike>(
);
return check_rights_cached(store, &parent, for_agent_enum, right, cache).await;
}
// No `parent` at all: the walk reached a root (a drive) without a
// grant. That is the ordinary answer "no", not a fault — the
// drive-first probe above lands here for every agent granted
// below the drive (an app's own agent on each `/app-write`), and
// so does a query filtering out members the agent cannot see.
// Logged at warn, it buried the case that is one.
Err(parent_err) if resource.get(urls::PARENT).is_err() => {
tracing::debug!(
subject = %resource.get_subject(),
agent = %for_agent,
?right,
%parent_err,
"rights walk: reached a root without a grant"
);
}
// A parent is named but could not be loaded (not synced yet, or
// missing). The walk cannot see the grants above it, so this is
// where a 401 for someone who does have rights originates.
Err(parent_err) => {
tracing::warn!(
subject = %resource.get_subject(),
agent = %for_agent,
?right,
parent_err = %parent_err,
"rights walk TERMINATED: get_parent failed (this is where the 401 originates)"
"rights walk TERMINATED: parent could not be loaded (this is where the 401 originates)"
);
}
}
Expand Down
112 changes: 112 additions & 0 deletions server/src/handlers/app_endpoints_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -525,3 +525,115 @@ async fn read_only_means_look_not_touch() {

assert_eq!(response.status(), 401, "{}", body_of(response));
}

/// What an app frame sends for `resource.remove(p).save()`: a `remove` op,
/// then a `save` of whatever else changed. The property has to be gone
/// afterwards, and stay gone through the next edit — which builds on the
/// stored Loro doc, where a removal that only reached the propvals returns.
#[actix_rt::test]
async fn an_app_removes_a_property_and_it_stays_removed() {
let (fixture, app) = app_fixture("app_write_remove").await;
let service = test::init_service(
App::new()
.app_data(Data::new(fixture.appstate.clone()))
.configure(crate::routes::config_routes),
)
.await;

let post = |payload: String| {
signed("/app-write", &fixture.appstate)
.method(actix_web::http::Method::POST)
.insert_header(("Content-Type", "application/json"))
.set_payload(payload)
.to_request()
};

// Shaped like an importing app's row (timesheets, notion): an import
// identity and a baseline, which the server checks on every write.
let values = serde_json::json!({ urls::NAME: "A note", urls::DESCRIPTION: "Goes away" });
let created = test::call_service(
&service,
post(
serde_json::json!({
"drive": fixture.drive,
"app": app,
"op": "create",
"propVals": {
urls::NAME: "A note",
urls::DESCRIPTION: "Goes away",
urls::LOCAL_ID: "source:1",
urls::IMPORT_BASELINE: { "values": values, "previous": {} },
},
})
.to_string(),
),
)
.await;
assert_eq!(created.status(), 200, "{}", body_of(created));
let written: serde_json::Value = serde_json::from_str(&body_of(created)).expect("json");
let subject = written["subject"].as_str().expect("a subject").to_string();

let removed = test::call_service(
&service,
post(format!(
r#"{{"drive":{:?},"app":{:?},"op":"remove","subject":{:?},"properties":[{:?}]}}"#,
fixture.drive,
app,
subject,
urls::DESCRIPTION,
)),
)
.await;
assert_eq!(removed.status(), 200, "{}", body_of(removed));

let description = |resource: &atomic_lib::Resource| {
resource.get(urls::DESCRIPTION).ok().map(|v| v.to_string())
};

let after_remove = fixture
.appstate
.store
.get_resource(&subject.as_str().into())
.await
.unwrap();
assert_eq!(
description(&after_remove),
None,
"the remove did not take effect"
);

let saved = test::call_service(
&service,
post(
serde_json::json!({
"drive": fixture.drive,
"app": app,
"op": "save",
"subject": subject,
"propVals": {
urls::NAME: "Renamed",
urls::IMPORT_BASELINE: {
"values": { urls::NAME: "Renamed", urls::DESCRIPTION: "Goes away" },
"previous": values,
},
},
})
.to_string(),
),
)
.await;
assert_eq!(saved.status(), 200, "{}", body_of(saved));

let after_save = fixture
.appstate
.store
.get_resource(&subject.as_str().into())
.await
.unwrap();
assert_eq!(after_save.get(urls::NAME).unwrap().to_string(), "Renamed");
assert_eq!(
description(&after_save),
None,
"the removed property came back on the next save"
);
}
Loading