diff --git a/AI-POLICY.md b/AI-POLICY.md index f9b9813c..bb9f979a 100644 --- a/AI-POLICY.md +++ b/AI-POLICY.md @@ -1,52 +1,36 @@ -# Policy on usage of Artificial Intelligence and other tools +# New policy on usage of Artificial Intelligence and other tools + +This project receives funding from [NLnet](https://nlnet.nl/), and has +done so since before NLnet introduced a GenAI policy. Now NLnet has published a [Version +2.0](https://nlnet.nl/foundation/policies/generativeAI/2.0/) of their policy. + +**Starting from 2026-12-04 I will adhere to this policy and stop allowing AI-generated contributions to this project**. One exception: if you're struck by a serious bug and have a PR that solves the problem for you, I will consider merging it. + +This policy will be evaluated in February. I do believe that AI-generation has been useful to this project. It may be that it's better for the project to forego the funding and keep vibing on - but I will decide on that later. + +# Old policy on usage of Artificial Intelligence and other tools + +This policy applies until 2026-12-04, and possibly after an evaluation in 2027-02. ## Read this first -The most important rule: be honest and inform about it! The -second-most important rule: YOU should add value to the project. That -value may be to find and reproduce a bug and verify that an -AI-generated fix solves the issue. +The most important rules: -If you ask the AI to "find some low-hanging fruit in the issue tracker -and generate a PR", then you're not adding value to the project. The -maintainer can probably do that himself, with a better overview of -what needs to be prioritized. Reviewing an AI-generated PR often -takes the maintainer more effort than doing the work directly. +1. You should (as a human) **write some sentences about why it's important for you** to get the PR approved. +2. **Be honest and inform about AI-usage.** +3. YOU should add value to the project. That value may be to find and + reproduce a bug and verify that an AI-generated fix solves the issue. -Keep a log of the prompts and/or commands used - this should be -included verbatim in the git commits as long as it's possible +**Prompts should be included verbatim in the git commits** as long as it's possible without making the messages too messy. When relevant, chat-output may -also need to be included or paraphrased. The `docs/design`-folder can -be used for dumping AI-generated design documents, code reviews, -prompts that are too large for being included in the commit message, -etc. +also need to be included. If that doesn't work out, then at least deliver the prompts paraphrased. + +The `docs/design`-folder can be used for dumping AI-generated design documents, code reviews, prompts that are too large for being included in the commit message, etc. If you think the rest of the document is too long to read, at least ask the AI to ensure the policy is followed. "YOU" in this document means the human, not the AI. -## NLnet funding and its GenAI policy - -This project receives funding from [NLnet](https://nlnet.nl/), and has -done so since before NLnet introduced a GenAI policy. The project is -currently committed to [version -1.1](https://nlnet.nl/foundation/policies/generativeAI/1.1/) of that -policy, which allows GenAI-assisted work as long as it is disclosed and -logged, and this document is written to fit it. [Version -2.0](https://nlnet.nl/foundation/policies/generativeAI/2.0/) of -2026-10-20 only allows GenAI to be used in a read-only manner (code -review, for instance), and NLnet wants it adopted. This document will -have to be revised if the project continues to receive NLnet funding. -Until that is settled, the rules below apply to all contributions. - -The priority is to deliver a good, feature-complete, easy-to-use and -bug-free library that stays compatible with as many servers as possible. -NLnet funding makes it possible for me to prioritize this, and spend -some hours a week rather than some hours a month on this project. -However, as the AI-models keep improving it may be questioned whether a -few hours a month of unfunded "vibe engineering" is of higher -value than a few hours a week of funded manual human labour. - ## Transparency matters If you've spent hours, perhaps a full day of your time writing up a @@ -145,7 +129,7 @@ Before I started to use the AI, I was aiming for "logical" commits containing in ## Future plans of GenAI-usage -I do want to go back to the old ways for doing the "core development tasks" - new features and complex refactoring. If nothing else, it's important for maintaining my brain cells, coding skills and making sure all the changes stick to my memory. The new policy is that GenAI-tools should be used mainly for improving quality, not speeding up the development. However, as my brain apparently has continued rotting due to extensive AI-usage, combined with improved models, I haven't been able to get back to "the old ways". +I do want to go back to the old ways for doing the "core development tasks" - new features and complex refactoring. If nothing else, it's important for maintaining my brain cells, coding skills and making sure all the changes stick to my memory. My own policy is that GenAI-tools should be used mainly for improving quality, not speeding up the development. However, as my brain apparently has continued rotting due to extensive AI-usage, combined with improved models, I haven't been able to get back to "the old ways". GenAI is very well suited for certain tasks, particularly anything that is either "mundane and tedious" or unrelated to "the working end" of the library. Examples: diff --git a/caldav/async_davclient.py b/caldav/async_davclient.py index f550e0a7..763f5f0f 100644 --- a/caldav/async_davclient.py +++ b/caldav/async_davclient.py @@ -991,9 +991,11 @@ async def get_calendars(self, principal: Optional["Principal"] = None) -> list[" props=self.CALENDAR_HOME_SET_PROPS, depth=0, ) - # Fetch calendars via PROPFIND, from the first URL that has any + # Fetch calendars via PROPFIND: from every home the server lists, + # or else from the first guessed URL that has any + calendar_home_urls, listed = self._calendar_home_urls(response, principal) calendars = [] - for n, calendar_home_url in enumerate(self._calendar_home_urls(response, principal)): + for n, calendar_home_url in enumerate(calendar_home_urls): auth = (self.auth, self.auth_type) try: response = await self.propfind( @@ -1001,15 +1003,26 @@ async def get_calendars(self, principal: Optional["Principal"] = None) -> list[" props=self.CALENDAR_LIST_PROPS, depth=1, ) + found = self._build_calendars_from_propfind(response, guess=n > 0 and not listed) except error.AuthorizationError: - # a refused guess means no calendars there; keep the auth - # that worked so far, which the refusal may have unwound + # a refused guess, or a refused extra home, means no + # calendars there; keep the auth that worked so far, + # which the refusal may have unwound if not n: raise self.auth, self.auth_type = auth + if listed: + continue break - calendars = self._build_calendars_from_propfind(response, guess=n > 0) - if calendars: + except error.DAVError as e: + # an extra home the server lists may be gone (a revoked + # share); that must not cost the user their own calendars + if not (n and listed): + raise + log.warning(f"skipping calendar home {calendar_home_url}: {e}") + continue + calendars.extend(found) + if found and not listed: break return calendars diff --git a/caldav/base_client.py b/caldav/base_client.py index c5352b1c..cfcedd66 100644 --- a/caldav/base_client.py +++ b/caldav/base_client.py @@ -600,28 +600,42 @@ def _rate_limit_sleep_seconds( # Pure result-handling shared by sync/async get_calendars; only the two # awaited PROPFIND calls and the principal lookup differ between the twins. - def _calendar_home_urls(self, home_set_response: Any, principal: Any) -> list[str]: - """Return absolute URLs to search for calendars, in order of preference. - - Without a calendar-home-set, try the principal URL, then the - client URL, which may be a calendar itself (e.g. Nextcloud public share). + def _calendar_home_urls(self, home_set_response: Any, principal: Any) -> tuple[list[str], bool]: + """Return absolute URLs to search for calendars, and whether they are listed. + + The URLs the server lists in calendar-home-set (RFC 4791 section + 6.2.1 allows several; Stalwart gives one per account sharing + calendars, ref https://github.com/python-caldav/caldav/issues/888) + are authoritative, and the calendars under all of them belong in the + answer. Without a calendar-home-set, the principal URL and then the + client URL, which may be a calendar itself (e.g. Nextcloud public + share), are guesses: the first one holding any calendars wins. The client root is moved to the host of the first URL, if it differs. """ - from caldav.collection import ( - _extract_calendar_home_set_from_results as extract_home_set, - ) + from caldav.collection import _extract_calendar_home_sets_from_results _raise_unless_propfind_ok(home_set_response) - calendar_home_url = extract_home_set(home_set_response.results, features=self.features) - if calendar_home_url: - urls = [self._make_absolute_url(calendar_home_url)] + home_sets = _extract_calendar_home_sets_from_results( + home_set_response.results, features=self.features + ) + listed = bool(home_sets) + if listed: + ## once each: a server may list one home in two spellings + urls = [] + seen = set() + for home_set in home_sets: + url = self._make_absolute_url(home_set) + key = URL.objectify(url).canonical() + if key not in seen: + seen.add(key) + urls.append(url) else: urls = [self._make_absolute_url(str(principal.url))] canonical = URL.objectify(urls[0]).canonical().strip_trailing_slash() if canonical != self.url.canonical().strip_trailing_slash(): urls.append(str(self.url)) self._follow_calendar_home(urls[0]) - return urls + return urls, listed def _follow_calendar_home(self, calendar_home_url: Any) -> None: """Move the client root to the host of the calendar-home-set. diff --git a/caldav/calendarobjectresource.py b/caldav/calendarobjectresource.py index be1bff79..9d3b2dc8 100644 --- a/caldav/calendarobjectresource.py +++ b/caldav/calendarobjectresource.py @@ -1219,7 +1219,6 @@ def _find_id_path(self, id=None, path=None) -> None: def _put( self, - retry_on_failure=True, precondition: Precondition = "auto", wildcard: Wildcard | None = None, ) -> "None | Coroutine[Any, Any, None]": @@ -1240,13 +1239,11 @@ def _put( ## The server drops a task's DTSTART unless it has a DUE (Zimbra) body = vcal.duration_as_due(str(body)) if self.is_async_client: - return self._async_send_put( - str(body), headers, retry_on_failure, precondition, wildcard - ) - return self._send_put(body, headers, retry_on_failure, precondition, wildcard) + return self._async_send_put(str(body), headers, precondition, wildcard) + return self._send_put(body, headers, precondition, wildcard) def _send_put( - self, body, headers, retry_on_failure, precondition: Precondition, wildcard: Wildcard | None + self, body, headers, precondition: Precondition, wildcard: Wildcard | None ) -> None: """The PUT of ``_put()`` and ``_put_raw()``, with what the answer says about a UID conflict (``_raise_uid_conflict``, @@ -1257,7 +1254,7 @@ def _send_put( self._raise_uid_conflict(e, wildcard is not None) raise try: - return self._post_put(r, retry_on_failure, precondition, wildcard) + return self._post_put(r, precondition, wildcard) except error.DAVError as e: if not isinstance(e, error.UidConflictError) and self._bare_uid_conflict( e.status, precondition, wildcard @@ -1266,7 +1263,7 @@ def _send_put( raise async def _async_send_put( - self, body, headers, retry_on_failure, precondition: Precondition, wildcard: Wildcard | None + self, body, headers, precondition: Precondition, wildcard: Wildcard | None ) -> None: try: r = await self.client.put(str(self.url), body, headers) @@ -1274,10 +1271,7 @@ async def _async_send_put( self._raise_uid_conflict(e, wildcard is not None) raise try: - result = self._post_put(r, retry_on_failure, precondition, wildcard) - if result is not None: - # _post_put returned a retry coroutine (self._put(False) for async client) - await result + self._post_put(r, precondition, wildcard) except error.DAVError as e: if not isinstance(e, error.UidConflictError) and self._bare_uid_conflict( e.status, precondition, wildcard @@ -1591,10 +1585,9 @@ async def _async_get_status(self, url) -> int | None: def _post_put( self, r, - retry_on_failure, precondition: Precondition = "auto", wildcard: Wildcard | None = None, - ) -> "None | Coroutine[Any, Any, None]": + ) -> None: if r.status >= 400: ## The UID is taken (RFC 4791 section 5.3.2.1): not something a ## retry would fix (issue #756). A 412 on a conditional save @@ -1636,36 +1629,11 @@ def _post_put( ## 15.4.4) - presumably the object, under a name of the server's self.url = self.url.relocate(urljoin(str(self.url), r.headers["Location"])) elif r.status not in (200, 201, 204): - ## No retry with a wildcard: an object this very PUT may have - ## stored (a 5xx after writing) would refuse If-None-Match: *, - ## and the failure is reported as it was for If-Match: * too. - ## Nor where it may be a taken UID: cleaning up the data does not free it. - ## A 5xx may also follow a successful write; retrying could mask - ## that uncertain outcome with a refusal from the second PUT. - ## Nor a redirect the client did not follow (another host or - ## port): nothing was stored, and another PUT is redirected too. - if ( - wildcard - or 300 <= r.status < 400 - or r.status >= 500 - or self._bare_uid_conflict(r.status, precondition, wildcard) - ): - retry_on_failure = False - if retry_on_failure: - try: - import vobject # noqa: F401 - except ImportError: - retry_on_failure = False - if retry_on_failure: - ## Accessing vobject_instance may "clean" the object. - ## See https://github.com/python-caldav/caldav/issues/43 - try: - self.get_vobject_instance() - except vobject.base.ParseError as exc: - raise error.error_from_response(error.PutError, r) from exc - return self._put(False, precondition, wildcard) - else: - raise error.error_from_response(error.PutError, r) + ## Not retried: the second PUT would send the same bytes, a 5xx + ## may follow a successful write, and only the second answer + ## would reach the caller, ref + ## https://github.com/python-caldav/caldav/issues/847 + raise error.error_from_response(error.PutError, r) if isinstance(getattr(r, "redirected_to", None), URL): ## Stored at the Location of a redirect (Zimbra: .ics) self.url = self.url.relocate(r.redirected_to) @@ -1677,10 +1645,7 @@ def _post_put( def _put_raw( self, body: bytes, precondition: Precondition = "auto", wildcard: Wildcard | None = None ) -> "None | Coroutine[Any, Any, None]": - """PUT ``body`` unchanged, for ``save(raw_data=...)``. - - Unlike ``_put()``, a failure is not retried with a cleaned-up - copy of the data: the caller asked for exactly these bytes.""" + """PUT ``body`` unchanged, for ``save(raw_data=...)``.""" if self.url is None: if not self.id: raise ValueError( @@ -1691,8 +1656,8 @@ def _put_raw( headers = self._put_headers(precondition, wildcard) body = WireBytes(body) if self.is_async_client: - return self._async_send_put(body, headers, False, precondition, wildcard) - return self._send_put(body, headers, False, precondition, wildcard) + return self._async_send_put(body, headers, precondition, wildcard) + return self._send_put(body, headers, precondition, wildcard) @staticmethod def _check_raw_data(raw_data: Any) -> bytes | None: @@ -1722,25 +1687,23 @@ def _create( self, id=None, path=None, - retry_on_failure=True, precondition: Precondition = "auto", wildcard: Wildcard | None = None, ) -> "None | Coroutine[Any, Any, None]": ## TODO: Find a better method name self._find_id_path(id=id, path=path) if self.is_async_client: - return self._async_create(retry_on_failure, precondition, wildcard) - self._put(retry_on_failure, precondition, wildcard) + return self._async_create(precondition, wildcard) + self._put(precondition, wildcard) return None async def _async_create( self, - retry_on_failure=True, precondition: Precondition = "auto", wildcard: Wildcard | None = None, ) -> None: """Async implementation of _create.""" - await self._put(retry_on_failure, precondition, wildcard) + await self._put(precondition, wildcard) def _generate_url(self): ## See https://github.com/python-caldav/caldav/issues/143 for the rationale behind double-quoting slashes diff --git a/caldav/collection.py b/caldav/collection.py index b2c0ffbb..61475946 100644 --- a/caldav/collection.py +++ b/caldav/collection.py @@ -217,15 +217,32 @@ def _sanitize_calendar_home_set_url(url: str | None, features: Any = None) -> st return urlunparse(parsed._replace(path=parsed.path.replace("@", "%40"))) -def _extract_calendar_home_set_from_results( +def _first_calendar_home_set(value: str | list[str] | None) -> str | None: + """The first href of a calendar-home-set property value. + + RFC 4791 section 6.2.1 allows several hrefs, and the parser then gives a + list. Stalwart lists the user's own home first, then one per account + sharing calendars with them, so the first is the one to create calendars + in, ref https://github.com/python-caldav/caldav/issues/888 + """ + if isinstance(value, list): + return value[0] if value else None + return value + + +def _extract_calendar_home_sets_from_results( results: list[Any] | None, features: Any = None -) -> str | None: - """Extract calendar-home-set URL from a list of PropfindResult objects.""" +) -> list[str]: + """Extract the calendar-home-set URLs from a list of PropfindResult objects. + + Usually one; RFC 4791 section 6.2.1 allows several, in the server's order. + """ for result in results or []: home_set = result.properties.get("{urn:ietf:params:xml:ns:caldav}calendar-home-set") if home_set: - return _sanitize_calendar_home_set_url(home_set, features=features) - return None + hrefs = home_set if isinstance(home_set, list) else [home_set] + return [_sanitize_calendar_home_set_url(h, features=features) for h in hrefs] + return [] class CalendarSet(DAVObject): @@ -585,7 +602,9 @@ async def _async_get_calendar_home_set(self) -> "CalendarSet": if self._calendar_home_set: return self._calendar_home_set - calendar_home_set_url = await self.get_property(cdav.CalendarHomeSet()) + calendar_home_set_url = _first_calendar_home_set( + await self.get_property(cdav.CalendarHomeSet()) + ) if calendar_home_set_url: self.calendar_home_set = _sanitize_calendar_home_set_url( calendar_home_set_url, features=self.client.features @@ -698,7 +717,9 @@ async def _async_get_vcal_address(self) -> "vCalAddress": @property def calendar_home_set(self): if not self._calendar_home_set: - calendar_home_set_url = self.get_property(cdav.CalendarHomeSet()) + calendar_home_set_url = _first_calendar_home_set( + self.get_property(cdav.CalendarHomeSet()) + ) if calendar_home_set_url: self.calendar_home_set = _sanitize_calendar_home_set_url( calendar_home_set_url, features=self.client.features diff --git a/caldav/davclient.py b/caldav/davclient.py index af7dac1c..58abe9d8 100644 --- a/caldav/davclient.py +++ b/caldav/davclient.py @@ -398,9 +398,11 @@ def get_calendars(self, principal: Principal | None = None) -> list[Calendar]: props=self.CALENDAR_HOME_SET_PROPS, depth=0, ) - # Fetch calendars via PROPFIND, from the first URL that has any + # Fetch calendars via PROPFIND: from every home the server lists, + # or else from the first guessed URL that has any + calendar_home_urls, listed = self._calendar_home_urls(response, principal) calendars = [] - for n, calendar_home_url in enumerate(self._calendar_home_urls(response, principal)): + for n, calendar_home_url in enumerate(calendar_home_urls): auth = (self.auth, self.auth_type) try: response = self.propfind( @@ -408,15 +410,26 @@ def get_calendars(self, principal: Principal | None = None) -> list[Calendar]: props=self.CALENDAR_LIST_PROPS, depth=1, ) + found = self._build_calendars_from_propfind(response, guess=n > 0 and not listed) except error.AuthorizationError: - # a refused guess means no calendars there; keep the auth - # that worked so far, which the refusal may have unwound + # a refused guess, or a refused extra home, means no + # calendars there; keep the auth that worked so far, + # which the refusal may have unwound if not n: raise self.auth, self.auth_type = auth + if listed: + continue break - calendars = self._build_calendars_from_propfind(response, guess=n > 0) - if calendars: + except error.DAVError as e: + # an extra home the server lists may be gone (a revoked + # share); that must not cost the user their own calendars + if not (n and listed): + raise + log.warning(f"skipping calendar home {calendar_home_url}: {e}") + continue + calendars.extend(found) + if found and not listed: break return calendars diff --git a/changes/847.fixed.md b/changes/847.fixed.md index 8d8ff566..911bee7e 100644 --- a/changes/847.fixed.md +++ b/changes/847.fixed.md @@ -1 +1 @@ -Do not retry a PUT after a server error: the server may already have stored the object, and a second refusal must not hide that uncertain outcome or cause safe recurring-task completion to delete its completion record. Preserve the original PUT error if vobject cannot parse the data while preparing a retry. +Do not retry a failed PUT. The retry sent the same data again, and only its answer reached the caller: after a server error the server may already have stored the object, so a second refusal hid that uncertain outcome and could make safe recurring-task completion delete its completion record. A save refused by the server now costs one request instead of two. diff --git a/changes/888.fixed.md b/changes/888.fixed.md new file mode 100644 index 00000000..377e5ffe --- /dev/null +++ b/changes/888.fixed.md @@ -0,0 +1 @@ +Support a `calendar-home-set` holding several hrefs, as RFC 4791 allows: `get_calendars()` now lists the calendars under every home the server names (Stalwart lists one per account sharing calendars with the user), while `principal.calendar_home_set`, where new calendars are created, is the first one. Both used to crash. diff --git a/docs/design/RETRY_AND_RESILIENCE_DESIGN.md b/docs/design/RETRY_AND_RESILIENCE_DESIGN.md index acb489b7..7d8929fa 100644 --- a/docs/design/RETRY_AND_RESILIENCE_DESIGN.md +++ b/docs/design/RETRY_AND_RESILIENCE_DESIGN.md @@ -71,7 +71,7 @@ wild from plann's panic postponement. That saves many tasks in a row, but one at a time, and Xandikos frees the lock before it answers, so plann cannot collide with itself: some other writer was busy at the same moment, and which one is unknown. A burst of saves only makes such a collision more likely. -The library already retried that PUT, but at once (see §4.6), so the lock was +The library used to retry that PUT, but at once (see §4.6), so the lock was still held and the 423 reached the caller. Two cases where retrying does not help: a real `LOCK` held by another client, which lasts until that client unlocks or the lock times out, which may be minutes; and a stale `index.lock` @@ -527,20 +527,18 @@ is unaffected by all of this, and niquests' `LeakyBucketLimiter` / `TokenBucketLimiter` are the obvious home for it if it ever moves into the library. -### 4.6 The immediate PUT retry in `_post_put` - -Separate from all of the above, `CalendarObjectResource._post_put()` retries a -failed PUT once, at once and without a sleep, when vobject is installed. It -is meant for data that the server rejected and that vobject's cleanup might -fix (https://github.com/python-caldav/caldav/issues/43), but it fires on -almost any status that is not 2xx or 3xx: only a UID conflict, a 412 and a -save sent with a wildcard (`If-None-Match: *` / `If-Match: *`) are left -alone. On a 423 (or a 503 without `Retry-After`, which -`raise_if_rate_limited()` lets through) it only sends the same PUT into the same -lock. Its other problem, that the first answer is hidden from the caller, is -https://github.com/python-caldav/caldav/issues/847. Whatever is decided there, -the immediate retry should leave the statuses of class (C) alone, so that the -retry logic of this design is the only one that acts on them. +### 4.6 The immediate PUT retry in `_post_put` (removed) + +`CalendarObjectResource._post_put()` used to retry a failed PUT once, at once +and without a sleep, when vobject was installed. It was meant for data that +the server rejected and that vobject's cleanup might fix +(https://github.com/python-caldav/caldav/issues/43), but by then the cleanup no +longer touched the body: the second PUT sent the same bytes, into the same +lock on a 423, and hid the first answer from the caller +(https://github.com/python-caldav/caldav/issues/847). It is gone, 5xx first +and then every status, so a failed PUT reaches the caller unchanged and the +retry logic of this design is the only one that can act on the statuses of +class (C). ## 5. Consequences for PR #648 diff --git a/tests/multi_home_set_fixtures.py b/tests/multi_home_set_fixtures.py new file mode 100644 index 00000000..e3f444bd --- /dev/null +++ b/tests/multi_home_set_fixtures.py @@ -0,0 +1,99 @@ +""" +Mocked PROPFIND responses shared by the sync and async unit tests of a +calendar-home-set holding several hrefs, ref +https://github.com/python-caldav/caldav/issues/888 + +Stalwart with WebDav.enableAssistedDiscovery off lists the user's own home +first, then one home per account sharing calendars with them. RFC 4791 +section 6.2.1 allows any number of hrefs in the property. +""" + +from urllib.parse import urlparse + +from caldav.lib.url import URL + +MULTI_HOME_ROOT = "https://stalwart.example.com/dav/" +MULTI_HOME_PRINCIPAL_URL = "https://stalwart.example.com/dav/pal/bob%40example.org/" +MULTI_HOME_OWN_HOME_URL = "https://stalwart.example.com/dav/cal/bob%40example.org/" +MULTI_HOME_SHARED_HOME_URL = "https://stalwart.example.com/dav/cal/jane%40example.org/" + +MULTI_HOME_SET_XML = """ + + /dav/pal/bob%40example.org/ + + /dav/cal/bob%40example.org//dav/cal/jane%40example.org/ + HTTP/1.1 200 OK + + +""" + + +def _calendar_list_xml(owner: str) -> str: + return f""" + + /dav/cal/{owner}%40example.org/default/ + + {owner} + HTTP/1.1 200 OK + + +""" + + +_RESPONSES = { + urlparse(MULTI_HOME_PRINCIPAL_URL).path: MULTI_HOME_SET_XML, + urlparse(MULTI_HOME_OWN_HOME_URL).path: _calendar_list_xml("bob"), + urlparse(MULTI_HOME_SHARED_HOME_URL).path: _calendar_list_xml("jane"), +} + +## What get_calendars() should return: every calendar under every home, +## the user's own first. Compare with canonical(): whether the library +## spells the "@" as "%40" is not what these tests are about. +MULTI_HOME_EXPECTED_CALENDARS = [ + MULTI_HOME_OWN_HOME_URL + "default/", + MULTI_HOME_SHARED_HOME_URL + "default/", +] + +## The requests get_calendars() should send: the home-set, then each home once. +MULTI_HOME_EXPECTED_REQUESTS = [ + MULTI_HOME_PRINCIPAL_URL, + MULTI_HOME_OWN_HOME_URL, + MULTI_HOME_SHARED_HOME_URL, +] + + +def multi_home_propfind_xml(url) -> str: + """The answer to a PROPFIND on url; an unknown url fails the test.""" + return _RESPONSES[urlparse(str(url)).path] + + +def canonical(urls) -> list[str]: + """The URLs in canonical form, so "@" and "%40" compare equal.""" + return [str(URL.objectify(str(u)).canonical()) for u in urls] + + +## A home the server lists may still refuse or have lost its calendars: a +## sharing account deleted, or the share revoked. get_calendars() should +## skip it and still return the user's own calendars. +MULTI_HOME_SHARED_HOME_FAILURES = [403, 404, 500] + +## The own home listed twice, once with "@" and once with "%40": queried once. +MULTI_HOME_SET_DUPLICATE_XML = MULTI_HOME_SET_XML.replace( + "/dav/cal/jane%40example.org/", + "/dav/cal/bob@example.org//dav/cal/jane%40example.org/", +) + + +def multi_home_answer( + url, shared_status: int = 207, duplicate_home: bool = False +) -> tuple[int, str]: + """The status and body of a PROPFIND on url. + + shared_status other than 207 makes the shared home answer that, with an + empty body; duplicate_home lists the own home twice in the home-set.""" + path = urlparse(str(url)).path + if shared_status != 207 and path == urlparse(MULTI_HOME_SHARED_HOME_URL).path: + return shared_status, "" + if duplicate_home and path == urlparse(MULTI_HOME_PRINCIPAL_URL).path: + return 207, MULTI_HOME_SET_DUPLICATE_XML + return 207, multi_home_propfind_xml(url) diff --git a/tests/test_async_davclient.py b/tests/test_async_davclient.py index 0f92d85f..cc0f7a81 100644 --- a/tests/test_async_davclient.py +++ b/tests/test_async_davclient.py @@ -15,6 +15,8 @@ from caldav.async_davclient import AsyncDAVClient, DAVResponse, get_davclient from caldav.lib import error +from .multi_home_set_fixtures import MULTI_HOME_SHARED_HOME_FAILURES + # Sample XML responses for testing SAMPLE_MULTISTATUS_XML = b""" @@ -1853,6 +1855,95 @@ async def fake_display_name(self: Calendar) -> str: await principal.calendar(name="Wanted") +class TestAsyncGetCalendarsMultipleHomeSets: + """Async twin of the sync tests of a calendar-home-set with several + hrefs, ref https://github.com/python-caldav/caldav/issues/888""" + + @staticmethod + def _client(**answer_options): + from .multi_home_set_fixtures import MULTI_HOME_ROOT, multi_home_answer + + client = AsyncDAVClient(url=MULTI_HOME_ROOT) + client.requests = [] + + async def fake_request(url, method="GET", body="", headers=None): + client.requests.append(str(url)) + status, xml = multi_home_answer(url, **answer_options) + return DAVResponse(create_mock_response(xml.encode(), status_code=status)) + + client.request = fake_request + return client + + @pytest.mark.asyncio + async def test_get_calendars_lists_every_home(self) -> None: + from caldav.collection import Principal + + from .multi_home_set_fixtures import ( + MULTI_HOME_EXPECTED_CALENDARS, + MULTI_HOME_EXPECTED_REQUESTS, + MULTI_HOME_PRINCIPAL_URL, + canonical, + ) + + client = self._client() + principal = Principal(client=client, url=MULTI_HOME_PRINCIPAL_URL) + calendars = await client.get_calendars(principal) + assert canonical(c.url for c in calendars) == canonical(MULTI_HOME_EXPECTED_CALENDARS) + assert canonical(client.requests) == canonical(MULTI_HOME_EXPECTED_REQUESTS) + + @pytest.mark.asyncio + @pytest.mark.parametrize("shared_status", MULTI_HOME_SHARED_HOME_FAILURES) + async def test_get_calendars_skips_failing_shared_home(self, shared_status) -> None: + from caldav.collection import Principal + + from .multi_home_set_fixtures import ( + MULTI_HOME_EXPECTED_CALENDARS, + MULTI_HOME_EXPECTED_REQUESTS, + MULTI_HOME_PRINCIPAL_URL, + canonical, + ) + + client = self._client(shared_status=shared_status) + auth = (client.auth, client.auth_type) + principal = Principal(client=client, url=MULTI_HOME_PRINCIPAL_URL) + calendars = await client.get_calendars(principal) + assert canonical(c.url for c in calendars) == canonical(MULTI_HOME_EXPECTED_CALENDARS[:1]) + assert canonical(client.requests) == canonical(MULTI_HOME_EXPECTED_REQUESTS) + assert (client.auth, client.auth_type) == auth + + @pytest.mark.asyncio + async def test_get_calendars_duplicate_home(self) -> None: + from caldav.collection import Principal + + from .multi_home_set_fixtures import ( + MULTI_HOME_EXPECTED_CALENDARS, + MULTI_HOME_EXPECTED_REQUESTS, + MULTI_HOME_PRINCIPAL_URL, + canonical, + ) + + client = self._client(duplicate_home=True) + principal = Principal(client=client, url=MULTI_HOME_PRINCIPAL_URL) + calendars = await client.get_calendars(principal) + assert canonical(c.url for c in calendars) == canonical(MULTI_HOME_EXPECTED_CALENDARS) + assert canonical(client.requests) == canonical(MULTI_HOME_EXPECTED_REQUESTS) + + @pytest.mark.asyncio + async def test_calendar_home_set_is_own_home(self) -> None: + from caldav.collection import Principal + + from .multi_home_set_fixtures import ( + MULTI_HOME_OWN_HOME_URL, + MULTI_HOME_PRINCIPAL_URL, + canonical, + ) + + client = self._client() + principal = Principal(client=client, url=MULTI_HOME_PRINCIPAL_URL) + home_set = await principal._async_get_calendar_home_set() + assert canonical([home_set.url]) == canonical([MULTI_HOME_OWN_HOME_URL]) + + class TestAsyncGetCalendarsWithoutHomeSet: """Async twin of the sync no-calendar-home-set discovery tests.""" diff --git a/tests/test_caldav_unit.py b/tests/test_caldav_unit.py index ed499155..ea54a0fb 100755 --- a/tests/test_caldav_unit.py +++ b/tests/test_caldav_unit.py @@ -33,6 +33,7 @@ from caldav.lib.python_utilities import to_normal_str, to_wire from caldav.lib.url import URL +from .multi_home_set_fixtures import MULTI_HOME_SHARED_HOME_FAILURES from .public_share_fixtures import ( GMX_LIKE_PRINCIPAL_DEPTH1_XML, PUBLIC_SHARE_PRINCIPAL_DEPTH1_XML, @@ -2342,6 +2343,100 @@ def testCalendarHomeSetOnOtherHost(self): "https://p49-caldav.example.com:443/123/calendars/cal/event.ics" ] + def testGetCalendarsMultipleHomeSets(self): + """RFC 4791 section 6.2.1 allows several hrefs in calendar-home-set; + get_calendars() lists the calendars under each of them, + ref https://github.com/python-caldav/caldav/issues/888""" + from .multi_home_set_fixtures import ( + MULTI_HOME_EXPECTED_CALENDARS, + MULTI_HOME_EXPECTED_REQUESTS, + MULTI_HOME_PRINCIPAL_URL, + MULTI_HOME_ROOT, + canonical, + multi_home_propfind_xml, + ) + + client = DAVClient(url=MULTI_HOME_ROOT) + requested = [] + + def fake_request(url, *largs, **kwargs): + requested.append(str(url)) + return MockedDAVResponse(multi_home_propfind_xml(url)) + + client.request = fake_request + principal = Principal(client=client, url=MULTI_HOME_PRINCIPAL_URL) + calendars = client.get_calendars(principal) + assert canonical(c.url for c in calendars) == canonical(MULTI_HOME_EXPECTED_CALENDARS) + assert canonical(requested) == canonical(MULTI_HOME_EXPECTED_REQUESTS) + + def _multi_home_client(self, **answer_options): + from .multi_home_set_fixtures import MULTI_HOME_ROOT, multi_home_answer + + client = DAVClient(url=MULTI_HOME_ROOT) + client.requests = [] + + def fake_request(url, *largs, **kwargs): + client.requests.append(str(url)) + status, body = multi_home_answer(url, **answer_options) + resp = mock.MagicMock() + resp.status_code = status + resp.reason = "multistatus" if status == 207 else "failed" + resp.headers = {} + resp.content = body + return DAVResponse(resp, client) + + client.request = fake_request + return client + + @pytest.mark.parametrize("shared_status", MULTI_HOME_SHARED_HOME_FAILURES) + def testGetCalendarsSkipsFailingSharedHome(self, shared_status): + """A listed home that is refused or gone does not cost the user + their own calendars, ref https://github.com/python-caldav/caldav/issues/888""" + from .multi_home_set_fixtures import ( + MULTI_HOME_EXPECTED_CALENDARS, + MULTI_HOME_EXPECTED_REQUESTS, + MULTI_HOME_PRINCIPAL_URL, + canonical, + ) + + client = self._multi_home_client(shared_status=shared_status) + auth = (client.auth, client.auth_type) + calendars = client.get_calendars(Principal(client=client, url=MULTI_HOME_PRINCIPAL_URL)) + assert canonical(c.url for c in calendars) == canonical(MULTI_HOME_EXPECTED_CALENDARS[:1]) + assert canonical(client.requests) == canonical(MULTI_HOME_EXPECTED_REQUESTS) + assert (client.auth, client.auth_type) == auth + + def testGetCalendarsDuplicateHome(self): + """A home listed twice is queried once""" + from .multi_home_set_fixtures import ( + MULTI_HOME_EXPECTED_CALENDARS, + MULTI_HOME_EXPECTED_REQUESTS, + MULTI_HOME_PRINCIPAL_URL, + canonical, + ) + + client = self._multi_home_client(duplicate_home=True) + calendars = client.get_calendars(Principal(client=client, url=MULTI_HOME_PRINCIPAL_URL)) + assert canonical(c.url for c in calendars) == canonical(MULTI_HOME_EXPECTED_CALENDARS) + assert canonical(client.requests) == canonical(MULTI_HOME_EXPECTED_REQUESTS) + + def testCalendarHomeSetMultipleHrefs(self): + """Principal.calendar_home_set is the user's own home - the first + href - when the server lists several, ref + https://github.com/python-caldav/caldav/issues/888""" + from .multi_home_set_fixtures import ( + MULTI_HOME_OWN_HOME_URL, + MULTI_HOME_PRINCIPAL_URL, + MULTI_HOME_ROOT, + canonical, + multi_home_propfind_xml, + ) + + client = DAVClient(url=MULTI_HOME_ROOT) + client.request = lambda url, *a, **kw: MockedDAVResponse(multi_home_propfind_xml(url)) + principal = Principal(client=client, url=MULTI_HOME_PRINCIPAL_URL) + assert canonical([principal.calendar_home_set.url]) == canonical([MULTI_HOME_OWN_HOME_URL]) + def testGetCalendarsOnOtherHost(self): """client.get_calendars() takes the calendar-home-set without the Principal setter, and must relocate the client root the same way, @@ -2714,10 +2809,8 @@ def test_save_none_falls_through_to_put_when_master_missing(self): """save(only_this_recurrence=None) calls _create() rather than raising when master absent.""" event, _ = self._make_orphan_event() created = [] - event._create = ( - lambda id=None, path=None, retry_on_failure=True, precondition="auto", wildcard=None: ( - created.append(True) - ) + event._create = lambda id=None, path=None, precondition="auto", wildcard=None: ( + created.append(True) ) event.save(only_this_recurrence=None) assert created, "_create() must be called (PUT as-is) when master not found" @@ -2726,10 +2819,8 @@ def test_save_false_bypasses_master_lookup(self): """save(only_this_recurrence=False) skips the master lookup entirely and PUTs directly.""" event, mock_calendar = self._make_orphan_event() created = [] - event._create = ( - lambda id=None, path=None, retry_on_failure=True, precondition="auto", wildcard=None: ( - created.append(True) - ) + event._create = lambda id=None, path=None, precondition="auto", wildcard=None: ( + created.append(True) ) event.save(only_this_recurrence=False) mock_calendar.get_event_by_uid.assert_not_called() @@ -2744,8 +2835,8 @@ def test_add_object_orphan_does_not_raise_notfound(self): created = [] original_create = CalendarObjectResource._create CalendarObjectResource._create = ( - lambda self_, id=None, path=None, retry_on_failure=True, precondition="auto", wildcard=None: ( - created.append(True) + lambda self_, id=None, path=None, precondition="auto", wildcard=None: created.append( + True ) ) try: @@ -2773,8 +2864,8 @@ def test_save_orphan_found_by_uid_does_not_recurse(self): with mock.patch.object( CalendarObjectResource, "_create", - lambda self_, id=None, path=None, retry_on_failure=True, precondition="auto", wildcard=None: ( - created.append(self_) + lambda self_, id=None, path=None, precondition="auto", wildcard=None: created.append( + self_ ), ): event.save() @@ -2808,7 +2899,6 @@ async def fake_create( self_, id=None, path=None, - retry_on_failure=True, precondition="auto", wildcard=None, ): @@ -3297,9 +3387,7 @@ def _put_sync(func): with mock.patch.object( CalendarObjectResource, "_create", - lambda self_, id=None, path=None, retry_on_failure=True, precondition="auto", wildcard=None: ( - put.append(self_) - ), + lambda self_, id=None, path=None, precondition="auto", wildcard=None: put.append(self_), ): func() assert len(put) == 1 @@ -3315,7 +3403,6 @@ async def fake_create( self_, id=None, path=None, - retry_on_failure=True, precondition="auto", wildcard=None, ): @@ -7961,28 +8048,25 @@ def test_save_does_not_retry_server_error(self, base, first_status, second_statu assert exc.value.status == first_status assert [method for method, _ in sent] == ["PUT"] - def test_save_preserves_refusal_when_vobject_cannot_parse(self, base, monkeypatch): - import vobject - - event, sent = self._event(base, status=403) - monkeypatch.setattr( - event, - "get_vobject_instance", - mock.Mock(side_effect=vobject.base.ParseError("cannot parse")), - ) + @pytest.mark.parametrize("first_status", [400, 403, 409]) + def test_save_does_not_retry_client_error(self, base, first_status): + """The second PUT would send the same bytes, and only its answer + would reach the caller, ref + https://github.com/python-caldav/caldav/issues/847""" + event, sent = self._event(base, status=[first_status, 204]) with pytest.raises(error.PutError) as exc: self._save(event) - assert exc.value.status == 403 + assert exc.value.status == first_status assert [method for method, _ in sent] == ["PUT"] - def test_save_precondition_etag_kept_on_retry(self, base) -> None: + def test_save_precondition_etag_on_refused_save(self, base) -> None: event, sent = self._event(base, schedule_tag='"stag-1"', status=[400, 204]) - self._save(event, precondition="etag") + with pytest.raises(error.PutError): + self._save(event, precondition="etag") puts = [headers for method, headers in sent if method == "PUT"] - assert len(puts) == 2 - for headers in puts: - assert headers["if-match"] == '"etag-a"' - assert "if-schedule-tag-match" not in headers + assert len(puts) == 1 + assert puts[0]["if-match"] == '"etag-a"' + assert "if-schedule-tag-match" not in puts[0] def test_save_precondition_etag_kept_on_recurrence_merge(self, base) -> None: """Saving one recurrence PUTs the master, which carries its own tags.""" @@ -8959,13 +9043,13 @@ def test_put_412_uid_conflict_with_schedule_tag(self, base) -> None: self._run(event.save()) assert isinstance(exc_info.value, error.ScheduleTagMismatchError) - def test_put_409_without_precondition_is_retried_once(self, base) -> None: + def test_put_409_without_precondition_is_not_retried(self, base) -> None: client, sent = self._client(base, 409) event = self._event(client) with pytest.raises(error.PutError) as exc_info: self._run(event.save()) assert not isinstance(exc_info.value, error.UidConflictError) - assert [m for m, _ in sent] == ["PUT", "PUT"] + assert [m for m, _ in sent] == ["PUT"] @mock.patch("caldav.davclient.requests.Session.request") def test_put_403_body_reaches_uid_conflict(self, mocked) -> None: @@ -9567,11 +9651,11 @@ def test_failure_not_retried_with_wildcard(self, base) -> None: self._run(self._event(client).save(no_overwrite=True)) assert [m for m, _ in sent] == ["PUT"] - def test_plain_save_bad_request_still_retried(self, base) -> None: + def test_plain_save_bad_request_not_retried(self, base) -> None: client, sent = self._client(base, put_status=400, features=self.NO_UID_CONFLICT) with pytest.raises(error.PutError): self._run(self._event(client).save()) - assert [m for m, _ in sent] == ["PUT", "PUT"] + assert [m for m, _ in sent] == ["PUT"] EV1_MULTISTATUS = (