render-lab-tasks-posthog 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1 @@
1
+ """Import .tasks explicitly to register durable tasks."""
@@ -0,0 +1,3 @@
1
+ from render import Workflows
2
+
3
+ app = Workflows()
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import POSTHOG_EXPORT_RETRY
6
+ from .types import AwaitExportInput, ExportResultDTO
7
+
8
+
9
+ async def await_export_impl(
10
+ ctx: TaskContext, input: AwaitExportInput, *, deps: Deps | None = None
11
+ ) -> ExportResultDTO:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.posthog.await_export(input)
14
+
15
+
16
+ @app.task(name="posthog.awaitExport", retry=POSTHOG_EXPORT_RETRY)
17
+ async def await_export(ctx: TaskContext, input: AwaitExportInput) -> ExportResultDTO:
18
+ return await await_export_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import POSTHOG_QUERY_RETRY
6
+ from .types import AwaitQueryInput, QueryResultDTO
7
+
8
+
9
+ async def await_query_impl(
10
+ ctx: TaskContext, input: AwaitQueryInput, *, deps: Deps | None = None
11
+ ) -> QueryResultDTO:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.posthog.await_query(input)
14
+
15
+
16
+ @app.task(name="posthog.awaitQuery", retry=POSTHOG_QUERY_RETRY)
17
+ async def await_query(ctx: TaskContext, input: AwaitQueryInput) -> QueryResultDTO:
18
+ return await await_query_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import POSTHOG_NO_RETRY
6
+ from .types import CaptureInput, IngestionResult
7
+
8
+
9
+ async def capture_impl(
10
+ ctx: TaskContext, input: CaptureInput, *, deps: Deps | None = None
11
+ ) -> IngestionResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.posthog.capture(input)
14
+
15
+
16
+ @app.task(name="posthog.capture", retry=POSTHOG_NO_RETRY)
17
+ async def capture(ctx: TaskContext, input: CaptureInput) -> IngestionResult:
18
+ return await capture_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import POSTHOG_NO_RETRY
6
+ from .types import CaptureBatchInput, IngestionResult
7
+
8
+
9
+ async def capture_batch_impl(
10
+ ctx: TaskContext, input: CaptureBatchInput, *, deps: Deps | None = None
11
+ ) -> IngestionResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.posthog.capture_batch(input)
14
+
15
+
16
+ @app.task(name="posthog.captureBatch", retry=POSTHOG_NO_RETRY)
17
+ async def capture_batch(ctx: TaskContext, input: CaptureBatchInput) -> IngestionResult:
18
+ return await capture_batch_impl(ctx, input)
@@ -0,0 +1,395 @@
1
+ """Injected vendor interface and one-attempt async HTTP adapter."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ import os
8
+ from collections.abc import AsyncIterator, Mapping
9
+ from contextlib import asynccontextmanager
10
+ from dataclasses import dataclass
11
+ from typing import Any, Literal, Protocol
12
+
13
+ import httpx
14
+ from render_lab_tasks_core.bounded import validate_byte_limit
15
+ from render_lab_tasks_core.http import (
16
+ HttpClient,
17
+ enc,
18
+ js_string,
19
+ nullish,
20
+ pick,
21
+ required,
22
+ )
23
+
24
+ from . import types as t
25
+
26
+
27
+ def obj(value: Any) -> dict[str, Any]:
28
+ return value if isinstance(value, dict) else {}
29
+
30
+
31
+ def numeric(value: Any) -> bool:
32
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
33
+
34
+
35
+ def remap(input: Mapping[str, Any], names: Mapping[str, str]) -> dict[str, Any]:
36
+ return {v: input[k] for k, v in names.items() if k in input}
37
+
38
+
39
+ def byte_count(value: Any) -> int:
40
+ return len(
41
+ json.dumps(value, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode()
42
+ )
43
+
44
+
45
+ def event_body(input: Mapping[str, Any]) -> dict[str, Any]:
46
+ return remap(
47
+ input,
48
+ {
49
+ "event": "event",
50
+ "distinctId": "distinct_id",
51
+ "properties": "properties",
52
+ "timestamp": "timestamp",
53
+ "eventId": "uuid",
54
+ },
55
+ )
56
+
57
+
58
+ def rollout(value: Any) -> None:
59
+ if value is None:
60
+ return
61
+ if not numeric(value) or not math.isfinite(value) or not 0 <= value <= 100:
62
+ raise ValueError(
63
+ f"rolloutPercentage must be between 0 and 100, received {js_string(value)}."
64
+ )
65
+
66
+
67
+ def flag_body(input: Mapping[str, Any]) -> dict[str, Any]:
68
+ body = pick(input, "key", "name", "active")
69
+ if "filters" in input:
70
+ body["filters"] = input["filters"]
71
+ elif input.get("rolloutPercentage") is not None:
72
+ body["filters"] = {
73
+ "groups": [{"properties": [], "rollout_percentage": input["rolloutPercentage"]}]
74
+ }
75
+ return body
76
+
77
+
78
+ def flag(value: Any) -> t.FeatureFlagDTO:
79
+ row = obj(value)
80
+ filters = obj(row.get("filters"))
81
+ groups = filters.get("groups")
82
+ group = obj(groups[0]) if isinstance(groups, list) and groups else {}
83
+ percent = (
84
+ row.get("rollout_percentage")
85
+ if numeric(row.get("rollout_percentage"))
86
+ else group.get("rollout_percentage")
87
+ )
88
+ return {
89
+ "id": row["id"] if numeric(row.get("id")) else 0,
90
+ "key": nullish(row.get("key"), ""),
91
+ "name": nullish(row.get("name"), ""),
92
+ "active": nullish(row.get("active"), False),
93
+ "filters": filters,
94
+ "rolloutPercentage": percent if numeric(percent) else None,
95
+ }
96
+
97
+
98
+ def export_status(row: Mapping[str, Any]) -> Literal["failed", "completed", "running"]:
99
+ return (
100
+ "failed"
101
+ if row.get("exception")
102
+ else "completed"
103
+ if row.get("has_content") is True
104
+ else "running"
105
+ )
106
+
107
+
108
+ class Port(Protocol):
109
+ async def await_export(self, input: t.AwaitExportInput) -> t.ExportResultDTO: ...
110
+ async def await_query(self, input: t.AwaitQueryInput) -> t.QueryResultDTO: ...
111
+ async def capture(self, input: t.CaptureInput) -> t.IngestionResult: ...
112
+ async def capture_batch(self, input: t.CaptureBatchInput) -> t.IngestionResult: ...
113
+ async def create_annotation(self, input: t.CreateAnnotationInput) -> t.AnnotationDTO: ...
114
+ async def create_export(self, input: t.CreateExportInput) -> t.ExportRunDTO: ...
115
+ async def create_feature_flag(self, input: t.CreateFeatureFlagInput) -> t.FeatureFlagDTO: ...
116
+ async def evaluate_flags(self, input: t.EvaluateFlagsInput) -> t.EvaluateFlagsResult: ...
117
+ async def group_identify(self, input: t.GroupIdentifyInput) -> t.IngestionResult: ...
118
+ async def identify(self, input: t.IdentifyInput) -> t.IngestionResult: ...
119
+ async def run_query(self, input: t.RunQueryInput) -> t.QueryRunDTO: ...
120
+ async def update_feature_flag(self, input: t.UpdateFeatureFlagInput) -> t.FeatureFlagDTO: ...
121
+
122
+
123
+ @dataclass(frozen=True)
124
+ class Deps:
125
+ posthog: Port
126
+
127
+
128
+ class Client:
129
+ def __init__(self, http: httpx.AsyncClient, env: Mapping[str, str] | None = None) -> None:
130
+ self.env = os.environ if env is None else env
131
+ self.http = http
132
+ self.api = HttpClient(http, self._host, label="PostHog API")
133
+
134
+ def _host(self) -> str:
135
+ return self.env.get("POSTHOG_HOST", "https://us.posthog.com").rstrip("/")
136
+
137
+ def _path(self, suffix: str) -> str:
138
+ return "/api/projects/" + enc(required(self.env, "POSTHOG_PROJECT_ID")) + suffix
139
+
140
+ def _auth(self) -> dict[str, str]:
141
+ return {"authorization": "Bearer " + required(self.env, "POSTHOG_PERSONAL_API_KEY")}
142
+
143
+ async def _ingest(self, body: Mapping[str, Any], path: str = "/capture/") -> None:
144
+ await self.api.call(
145
+ path,
146
+ method="POST",
147
+ body={"api_key": required(self.env, "POSTHOG_PROJECT_API_KEY"), **body},
148
+ )
149
+
150
+ async def capture(self, input: t.CaptureInput) -> t.IngestionResult:
151
+ await self._ingest(event_body(input))
152
+ return {"accepted": True, "eventCount": 1}
153
+
154
+ async def capture_batch(self, input: t.CaptureBatchInput) -> t.IngestionResult:
155
+ n = len(input["events"])
156
+ if not 1 <= n <= 500:
157
+ raise ValueError(f"captureBatch accepts 1..500 events, received {n}.")
158
+ size = byte_count(input["events"])
159
+ if size > 3500000:
160
+ raise ValueError(
161
+ f"captureBatch serialized body is {size} bytes, above the "
162
+ f"limit of 3500000. Send fewer events per batch."
163
+ )
164
+ await self._ingest({"batch": [event_body(e) for e in input["events"]]}, "/batch/")
165
+ return {"accepted": True, "eventCount": n}
166
+
167
+ async def identify(self, input: t.IdentifyInput) -> t.IngestionResult:
168
+ await self._ingest(
169
+ {
170
+ "event": "$identify",
171
+ "distinct_id": input["distinctId"],
172
+ "properties": remap(
173
+ input, {"properties": "$set", "propertiesSetOnce": "$set_once"}
174
+ ),
175
+ **remap(input, {"eventId": "uuid"}),
176
+ }
177
+ )
178
+ return {"accepted": True, "eventCount": 1}
179
+
180
+ async def group_identify(self, input: t.GroupIdentifyInput) -> t.IngestionResult:
181
+ await self._ingest(
182
+ {
183
+ "event": "$groupidentify",
184
+ "distinct_id": input["groupKey"],
185
+ "properties": {
186
+ "$group_type": input["groupType"],
187
+ "$group_key": input["groupKey"],
188
+ "$group_set": input["properties"],
189
+ },
190
+ **remap(input, {"eventId": "uuid"}),
191
+ }
192
+ )
193
+ return {"accepted": True, "eventCount": 1}
194
+
195
+ async def evaluate_flags(self, input: t.EvaluateFlagsInput) -> t.EvaluateFlagsResult:
196
+ row = obj(
197
+ await self.api.call(
198
+ "/flags/?v=2",
199
+ method="POST",
200
+ body={
201
+ "api_key": required(self.env, "POSTHOG_PROJECT_API_KEY"),
202
+ **remap(
203
+ input,
204
+ {
205
+ "distinctId": "distinct_id",
206
+ "groups": "groups",
207
+ "personProperties": "person_properties",
208
+ "groupProperties": "group_properties",
209
+ },
210
+ ),
211
+ },
212
+ )
213
+ )
214
+ flags: list[t.FlagEvaluationDTO] = []
215
+ for key, value in obj(row.get("flags")).items():
216
+ value = obj(value)
217
+ reason = value.get("reason")
218
+ flags.append(
219
+ {
220
+ "key": key,
221
+ "enabled": nullish(value.get("enabled"), False),
222
+ "variant": value.get("variant")
223
+ if isinstance(value.get("variant"), (str, bool))
224
+ else None,
225
+ "reason": reason
226
+ if isinstance(reason, str)
227
+ else nullish(obj(reason).get("description"), obj(reason).get("code")),
228
+ }
229
+ )
230
+ return {"flags": flags}
231
+
232
+ async def create_feature_flag(self, input: t.CreateFeatureFlagInput) -> t.FeatureFlagDTO:
233
+ rollout(input.get("rolloutPercentage"))
234
+ return flag(
235
+ await self.api.call(
236
+ self._path("/feature_flags/"),
237
+ method="POST",
238
+ headers=self._auth(),
239
+ body=flag_body(input),
240
+ )
241
+ )
242
+
243
+ async def update_feature_flag(self, input: t.UpdateFeatureFlagInput) -> t.FeatureFlagDTO:
244
+ if not any(k in input for k in ("name", "active", "filters", "rolloutPercentage")):
245
+ raise ValueError(
246
+ "updateFeatureFlag requires at least one of name, "
247
+ "active, filters, or rolloutPercentage."
248
+ )
249
+ rollout(input.get("rolloutPercentage"))
250
+ return flag(
251
+ await self.api.call(
252
+ self._path("/feature_flags/" + enc(input["flagId"]) + "/"),
253
+ method="PATCH",
254
+ headers=self._auth(),
255
+ body=flag_body(input),
256
+ )
257
+ )
258
+
259
+ async def run_query(self, input: t.RunQueryInput) -> t.QueryRunDTO:
260
+ if not input["clientQueryId"].strip():
261
+ raise ValueError("runQuery requires a nonempty clientQueryId.")
262
+ row = obj(
263
+ await self.api.call(
264
+ self._path("/query/"),
265
+ method="POST",
266
+ headers=self._auth(),
267
+ body={
268
+ "query": input["query"],
269
+ "client_query_id": input["clientQueryId"],
270
+ "refresh": "force_async",
271
+ **pick(input, "name"),
272
+ },
273
+ )
274
+ )
275
+ status = obj(nullish(row.get("query_status"), row))
276
+ return {
277
+ "queryId": nullish(status.get("id"), input["clientQueryId"]),
278
+ "complete": status.get("complete") is True,
279
+ "error": status.get("error") is True,
280
+ "errorMessage": status.get("error_message"),
281
+ }
282
+
283
+ async def await_query(self, input: t.AwaitQueryInput) -> t.QueryResultDTO:
284
+ limit = validate_byte_limit(input.get("maxResultBytes", 1000000), 3500000)
285
+ row = obj(
286
+ await self.api.call(
287
+ self._path("/query/" + enc(input["queryId"]) + "/"), headers=self._auth()
288
+ )
289
+ )
290
+ status = obj(nullish(row.get("query_status"), row))
291
+ if status.get("error") is True:
292
+ raise RuntimeError(
293
+ f"PostHog query {input['queryId']} failed: "
294
+ f"{nullish(status.get('error_message'), 'unknown error')}."
295
+ )
296
+ if status.get("complete") is not True:
297
+ raise RuntimeError(f"PostHog query {input['queryId']} is still running.")
298
+ result = status.get("results")
299
+ size = byte_count(result)
300
+ if size > limit:
301
+ raise ValueError(
302
+ f"PostHog query {input['queryId']} result is {size} "
303
+ f"bytes, which exceeds maxResultBytes of {limit}. Narrow "
304
+ f"the query or request fewer rows."
305
+ )
306
+ return {
307
+ "queryId": input["queryId"],
308
+ "complete": True,
309
+ "error": False,
310
+ "errorMessage": None,
311
+ "results": result,
312
+ "byteCount": size,
313
+ }
314
+
315
+ async def create_export(self, input: t.CreateExportInput) -> t.ExportRunDTO:
316
+ if sum(k in input for k in ("insightId", "dashboardId", "query")) != 1:
317
+ raise ValueError(
318
+ "createExport requires exactly one of insightId, dashboardId, or query."
319
+ )
320
+ body = remap(
321
+ input,
322
+ {"exportFormat": "export_format", "insightId": "insight", "dashboardId": "dashboard"},
323
+ )
324
+ if "query" in input:
325
+ body["export_context"] = {"source": input["query"]}
326
+ row = obj(
327
+ await self.api.call(
328
+ self._path("/exports/"), method="POST", headers=self._auth(), body=body
329
+ )
330
+ )
331
+ return {"exportId": js_string(nullish(row.get("id"), "")), "status": export_status(row)}
332
+
333
+ async def await_export(self, input: t.AwaitExportInput) -> t.ExportResultDTO:
334
+ id = input["exportId"]
335
+ row = obj(
336
+ await self.api.call(self._path("/exports/" + enc(id) + "/"), headers=self._auth())
337
+ )
338
+ status = export_status(row)
339
+ if status == "failed":
340
+ raise RuntimeError(f"PostHog export {id} failed.")
341
+ if status != "completed":
342
+ raise RuntimeError(f"PostHog export {id} is still {status}.")
343
+ async with self.http.stream(
344
+ "GET",
345
+ self._host() + self._path("/exports/" + enc(id) + "/content/"),
346
+ headers=self._auth(),
347
+ follow_redirects=False,
348
+ ) as response:
349
+ url = response.headers.get("location")
350
+ if not 300 <= response.status_code < 400 or not url:
351
+ raise RuntimeError(
352
+ f"PostHog export {id} content did not redirect to a "
353
+ f"download URL (status {response.status_code})."
354
+ )
355
+ return {"exportId": id, "status": "completed", "downloadUrl": url}
356
+
357
+ async def create_annotation(self, input: t.CreateAnnotationInput) -> t.AnnotationDTO:
358
+ row = obj(
359
+ await self.api.call(
360
+ self._path("/annotations/"),
361
+ method="POST",
362
+ headers=self._auth(),
363
+ body=remap(
364
+ input,
365
+ {
366
+ "content": "content",
367
+ "dateMarker": "date_marker",
368
+ "scope": "scope",
369
+ "dashboardItemId": "dashboard_item",
370
+ },
371
+ ),
372
+ )
373
+ )
374
+ return {
375
+ "id": row["id"] if numeric(row.get("id")) else 0,
376
+ "content": nullish(row.get("content"), input["content"]),
377
+ "dateMarker": nullish(row.get("date_marker"), ""),
378
+ "scope": nullish(row.get("scope"), input.get("scope", "project")),
379
+ }
380
+
381
+
382
+ @asynccontextmanager
383
+ async def dependencies(deps: Deps | None) -> AsyncIterator[Deps]:
384
+ if deps is not None:
385
+ yield deps
386
+ else:
387
+ async with httpx.AsyncClient(
388
+ timeout=30, transport=httpx.AsyncHTTPTransport(retries=0)
389
+ ) as http:
390
+ yield Deps(posthog=Client(http))
391
+
392
+
393
+ PosthogPort = Port
394
+ PosthogClient = Client
395
+ PosthogDeps = Deps
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import POSTHOG_NO_RETRY
6
+ from .types import AnnotationDTO, CreateAnnotationInput
7
+
8
+
9
+ async def create_annotation_impl(
10
+ ctx: TaskContext, input: CreateAnnotationInput, *, deps: Deps | None = None
11
+ ) -> AnnotationDTO:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.posthog.create_annotation(input)
14
+
15
+
16
+ @app.task(name="posthog.createAnnotation", retry=POSTHOG_NO_RETRY)
17
+ async def create_annotation(ctx: TaskContext, input: CreateAnnotationInput) -> AnnotationDTO:
18
+ return await create_annotation_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import POSTHOG_NO_RETRY
6
+ from .types import CreateExportInput, ExportRunDTO
7
+
8
+
9
+ async def create_export_impl(
10
+ ctx: TaskContext, input: CreateExportInput, *, deps: Deps | None = None
11
+ ) -> ExportRunDTO:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.posthog.create_export(input)
14
+
15
+
16
+ @app.task(name="posthog.createExport", retry=POSTHOG_NO_RETRY)
17
+ async def create_export(ctx: TaskContext, input: CreateExportInput) -> ExportRunDTO:
18
+ return await create_export_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import POSTHOG_NO_RETRY
6
+ from .types import CreateFeatureFlagInput, FeatureFlagDTO
7
+
8
+
9
+ async def create_feature_flag_impl(
10
+ ctx: TaskContext, input: CreateFeatureFlagInput, *, deps: Deps | None = None
11
+ ) -> FeatureFlagDTO:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.posthog.create_feature_flag(input)
14
+
15
+
16
+ @app.task(name="posthog.createFeatureFlag", retry=POSTHOG_NO_RETRY)
17
+ async def create_feature_flag(ctx: TaskContext, input: CreateFeatureFlagInput) -> FeatureFlagDTO:
18
+ return await create_feature_flag_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import POSTHOG_RETRY
6
+ from .types import EvaluateFlagsInput, EvaluateFlagsResult
7
+
8
+
9
+ async def evaluate_flags_impl(
10
+ ctx: TaskContext, input: EvaluateFlagsInput, *, deps: Deps | None = None
11
+ ) -> EvaluateFlagsResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.posthog.evaluate_flags(input)
14
+
15
+
16
+ @app.task(name="posthog.evaluateFlags", retry=POSTHOG_RETRY)
17
+ async def evaluate_flags(ctx: TaskContext, input: EvaluateFlagsInput) -> EvaluateFlagsResult:
18
+ return await evaluate_flags_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import POSTHOG_NO_RETRY
6
+ from .types import GroupIdentifyInput, IngestionResult
7
+
8
+
9
+ async def group_identify_impl(
10
+ ctx: TaskContext, input: GroupIdentifyInput, *, deps: Deps | None = None
11
+ ) -> IngestionResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.posthog.group_identify(input)
14
+
15
+
16
+ @app.task(name="posthog.groupIdentify", retry=POSTHOG_NO_RETRY)
17
+ async def group_identify(ctx: TaskContext, input: GroupIdentifyInput) -> IngestionResult:
18
+ return await group_identify_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import POSTHOG_NO_RETRY
6
+ from .types import IdentifyInput, IngestionResult
7
+
8
+
9
+ async def identify_impl(
10
+ ctx: TaskContext, input: IdentifyInput, *, deps: Deps | None = None
11
+ ) -> IngestionResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.posthog.identify(input)
14
+
15
+
16
+ @app.task(name="posthog.identify", retry=POSTHOG_NO_RETRY)
17
+ async def identify(ctx: TaskContext, input: IdentifyInput) -> IngestionResult:
18
+ return await identify_impl(ctx, input)
File without changes
@@ -0,0 +1,6 @@
1
+ from render import Retry
2
+
3
+ POSTHOG_EXPORT_RETRY = Retry(max_retries=480, wait_duration_ms=15000, backoff_scaling=1)
4
+ POSTHOG_QUERY_RETRY = Retry(max_retries=360, wait_duration_ms=5000, backoff_scaling=1)
5
+ POSTHOG_NO_RETRY = Retry(max_retries=0, wait_duration_ms=1000, backoff_scaling=1)
6
+ POSTHOG_RETRY = Retry(max_retries=3, wait_duration_ms=1000, backoff_scaling=2)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import POSTHOG_NO_RETRY
6
+ from .types import QueryRunDTO, RunQueryInput
7
+
8
+
9
+ async def run_query_impl(
10
+ ctx: TaskContext, input: RunQueryInput, *, deps: Deps | None = None
11
+ ) -> QueryRunDTO:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.posthog.run_query(input)
14
+
15
+
16
+ @app.task(name="posthog.runQuery", retry=POSTHOG_NO_RETRY)
17
+ async def run_query(ctx: TaskContext, input: RunQueryInput) -> QueryRunDTO:
18
+ return await run_query_impl(ctx, input)
@@ -0,0 +1,41 @@
1
+ from ._app import app
2
+ from .await_export import await_export, await_export_impl
3
+ from .await_query import await_query, await_query_impl
4
+ from .capture import capture, capture_impl
5
+ from .capture_batch import capture_batch, capture_batch_impl
6
+ from .create_annotation import create_annotation, create_annotation_impl
7
+ from .create_export import create_export, create_export_impl
8
+ from .create_feature_flag import create_feature_flag, create_feature_flag_impl
9
+ from .evaluate_flags import evaluate_flags, evaluate_flags_impl
10
+ from .group_identify import group_identify, group_identify_impl
11
+ from .identify import identify, identify_impl
12
+ from .run_query import run_query, run_query_impl
13
+ from .update_feature_flag import update_feature_flag, update_feature_flag_impl
14
+
15
+ __all__ = [
16
+ "app",
17
+ "await_export",
18
+ "await_export_impl",
19
+ "await_query",
20
+ "await_query_impl",
21
+ "capture",
22
+ "capture_impl",
23
+ "capture_batch",
24
+ "capture_batch_impl",
25
+ "create_annotation",
26
+ "create_annotation_impl",
27
+ "create_export",
28
+ "create_export_impl",
29
+ "create_feature_flag",
30
+ "create_feature_flag_impl",
31
+ "evaluate_flags",
32
+ "evaluate_flags_impl",
33
+ "group_identify",
34
+ "group_identify_impl",
35
+ "identify",
36
+ "identify_impl",
37
+ "run_query",
38
+ "run_query_impl",
39
+ "update_feature_flag",
40
+ "update_feature_flag_impl",
41
+ ]
@@ -0,0 +1,147 @@
1
+ """JSON contracts ported from the pinned TypeScript pack."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal, NotRequired, TypedDict
6
+
7
+ type JsonValue = str | float | bool | None | list[JsonValue] | dict[str, JsonValue]
8
+
9
+ type JsonObject = dict[str, JsonValue]
10
+
11
+
12
+ class CaptureInput(TypedDict):
13
+ event: str
14
+ distinctId: str
15
+ properties: NotRequired[JsonObject]
16
+ timestamp: NotRequired[str]
17
+ eventId: NotRequired[str]
18
+
19
+
20
+ class CaptureBatchInput(TypedDict):
21
+ events: list[CaptureInput]
22
+
23
+
24
+ class IngestionResult(TypedDict):
25
+ accepted: Literal[True]
26
+ eventCount: float
27
+
28
+
29
+ class IdentifyInput(TypedDict):
30
+ distinctId: str
31
+ properties: JsonObject
32
+ propertiesSetOnce: NotRequired[JsonObject]
33
+ eventId: NotRequired[str]
34
+
35
+
36
+ class GroupIdentifyInput(TypedDict):
37
+ groupType: str
38
+ groupKey: str
39
+ properties: JsonObject
40
+ eventId: NotRequired[str]
41
+
42
+
43
+ class EvaluateFlagsInput(TypedDict):
44
+ distinctId: str
45
+ groups: NotRequired[dict[str, str]]
46
+ personProperties: NotRequired[JsonObject]
47
+ groupProperties: NotRequired[dict[str, JsonObject]]
48
+
49
+
50
+ class FlagEvaluationDTO(TypedDict):
51
+ key: str
52
+ enabled: bool
53
+ variant: str | bool | None
54
+ reason: str | None
55
+
56
+
57
+ class EvaluateFlagsResult(TypedDict):
58
+ flags: list[FlagEvaluationDTO]
59
+
60
+
61
+ class FeatureFlagDTO(TypedDict):
62
+ id: float
63
+ key: str
64
+ name: str
65
+ active: bool
66
+ filters: JsonObject
67
+ rolloutPercentage: float | None
68
+
69
+
70
+ class CreateFeatureFlagInput(TypedDict):
71
+ key: str
72
+ name: str
73
+ active: NotRequired[bool]
74
+ filters: NotRequired[JsonObject]
75
+ rolloutPercentage: NotRequired[float]
76
+
77
+
78
+ class UpdateFeatureFlagInput(TypedDict):
79
+ flagId: float
80
+ name: NotRequired[str]
81
+ active: NotRequired[bool]
82
+ filters: NotRequired[JsonObject]
83
+ rolloutPercentage: NotRequired[float | None]
84
+
85
+
86
+ class RunQueryInput(TypedDict):
87
+ query: JsonObject
88
+ clientQueryId: str
89
+ name: NotRequired[str]
90
+ maxResultBytes: NotRequired[float]
91
+
92
+
93
+ class QueryRunDTO(TypedDict):
94
+ queryId: str
95
+ complete: bool
96
+ error: bool
97
+ errorMessage: str | None
98
+
99
+
100
+ class AwaitQueryInput(TypedDict):
101
+ queryId: str
102
+ maxResultBytes: NotRequired[float]
103
+
104
+
105
+ class QueryResultDTO(TypedDict):
106
+ queryId: str
107
+ error: bool
108
+ errorMessage: str | None
109
+ complete: Literal[True]
110
+ results: JsonValue
111
+ byteCount: float
112
+
113
+
114
+ class CreateExportInput(TypedDict):
115
+ exportFormat: Literal["csv"] | Literal["xlsx"]
116
+ insightId: NotRequired[float]
117
+ dashboardId: NotRequired[float]
118
+ query: NotRequired[JsonObject]
119
+
120
+
121
+ class ExportRunDTO(TypedDict):
122
+ exportId: str
123
+ status: Literal["pending"] | Literal["running"] | Literal["completed"] | Literal["failed"]
124
+
125
+
126
+ class AwaitExportInput(TypedDict):
127
+ exportId: str
128
+
129
+
130
+ class ExportResultDTO(TypedDict):
131
+ exportId: str
132
+ status: Literal["completed"]
133
+ downloadUrl: str
134
+
135
+
136
+ class CreateAnnotationInput(TypedDict):
137
+ content: str
138
+ dateMarker: NotRequired[str]
139
+ scope: NotRequired[Literal["project"] | Literal["organization"]]
140
+ dashboardItemId: NotRequired[float]
141
+
142
+
143
+ class AnnotationDTO(TypedDict):
144
+ id: float
145
+ content: str
146
+ dateMarker: str
147
+ scope: str
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import POSTHOG_RETRY
6
+ from .types import FeatureFlagDTO, UpdateFeatureFlagInput
7
+
8
+
9
+ async def update_feature_flag_impl(
10
+ ctx: TaskContext, input: UpdateFeatureFlagInput, *, deps: Deps | None = None
11
+ ) -> FeatureFlagDTO:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.posthog.update_feature_flag(input)
14
+
15
+
16
+ @app.task(name="posthog.updateFeatureFlag", retry=POSTHOG_RETRY)
17
+ async def update_feature_flag(ctx: TaskContext, input: UpdateFeatureFlagInput) -> FeatureFlagDTO:
18
+ return await update_feature_flag_impl(ctx, input)
@@ -0,0 +1,86 @@
1
+ Metadata-Version: 2.5
2
+ Name: render-lab-tasks-posthog
3
+ Version: 0.1.0
4
+ Summary: posthog tasks for Render Workflows
5
+ Project-URL: Repository, https://github.com/render-lab/render-tasks-python
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.12
9
+ Requires-Dist: httpx<0.29,>=0.28
10
+ Requires-Dist: render-lab-tasks-core<0.2,>=0.1.1
11
+ Requires-Dist: render==1.0.1
12
+ Description-Content-Type: text/markdown
13
+
14
+ # render-lab-tasks-posthog
15
+
16
+ Unreleased Python port: **12 registered tasks** from
17
+ [render-lab/render-tasks](https://github.com/render-lab/render-tasks/tree/45f9c2d44bd28e01ae9813e0d2ff56ee6c533816/packages/tasks-posthog).
18
+ Python 3.12+, Render SDK 1.0.1. Requires core 0.1.1 or later.
19
+
20
+ From the repository root:
21
+
22
+ ```sh
23
+ uv sync --all-packages --locked
24
+ ```
25
+
26
+ Import `render_lab_tasks_posthog.tasks` to register tasks. The package root is inert.
27
+ Compose the exported `app` with `Workflows.from_workflows`; call tasks through
28
+ `ctx.run`. Every operation also exports `*_impl(ctx, input, *, deps=None)` for
29
+ injection. `Client(http, env)` accepts a caller-owned HTTPX client, and
30
+ `Deps(posthog=client)` injects it. Default dependencies open and close the HTTP
31
+ client per invocation; credentials are read lazily at use. No HTTP retries or
32
+ background vendor polling occur; `retry.py` owns the durable retry policies.
33
+
34
+ ## Task surface
35
+
36
+ | Registered task | Python export |
37
+ | --- | --- |
38
+ | `posthog.awaitExport` | `await_export` |
39
+ | `posthog.awaitQuery` | `await_query` |
40
+ | `posthog.capture` | `capture` |
41
+ | `posthog.captureBatch` | `capture_batch` |
42
+ | `posthog.createAnnotation` | `create_annotation` |
43
+ | `posthog.createExport` | `create_export` |
44
+ | `posthog.createFeatureFlag` | `create_feature_flag` |
45
+ | `posthog.evaluateFlags` | `evaluate_flags` |
46
+ | `posthog.groupIdentify` | `group_identify` |
47
+ | `posthog.identify` | `identify` |
48
+ | `posthog.runQuery` | `run_query` |
49
+ | `posthog.updateFeatureFlag` | `update_feature_flag` |
50
+
51
+ Typed JSON inputs and results are in `types.py`. Task names and JSON field names
52
+ match the pinned source; Python function names use snake_case.
53
+
54
+ ## Environment
55
+
56
+ | Variable | Requirement |
57
+ | --- | --- |
58
+ | `POSTHOG_HOST` | Optional; https://us.posthog.com by default; choose the account region. |
59
+ | `POSTHOG_PROJECT_API_KEY` | Required for ingestion and flag evaluation. |
60
+ | `POSTHOG_PERSONAL_API_KEY` | Required for flag management, queries, exports, and annotations. |
61
+ | `POSTHOG_PROJECT_ID` | Required for management endpoints. |
62
+
63
+ ## Behavior and limits
64
+
65
+ Project keys are sent only in ingestion/evaluation bodies; management uses the personal bearer token. Ingestion and non-idempotent creates disable retries. Batch input is capped at 500 events and 3.5 MB; query results default to 1 MB with a 3.5 MB ceiling. Export completion reads a redirect Location without downloading file bytes or forwarding credentials to storage. A returned URL is an opaque vendor value; its lifetime and accessibility need live checks.
66
+
67
+ ## Verification
68
+
69
+ All registered tasks have hermetic contract fixtures executed independently against
70
+ the pinned TS implementation. SDK-backed tasks also have explicit HTTP request
71
+ fixtures. See `tests/test_batch3_contracts.py` and `tests/test_batch3_edges.py`.
72
+ These are not live vendor results.
73
+
74
+ Vendor webhooks subpaths and other registration-free TS exports are outside this
75
+ batch unless explicitly listed above. Full registered-task coverage does not
76
+ imply all supporting exports are ported.
77
+
78
+ Pending scopes, test resources, replay, and hosted checks are in the
79
+ [live-testing backlog](https://github.com/render-lab/render-tasks-python/issues/1)
80
+ and [verification tracker](../../docs/verification-tracker.md).
81
+
82
+ ## Installation
83
+
84
+ ```sh
85
+ pip install render-lab-tasks-posthog==0.1.0
86
+ ```
@@ -0,0 +1,23 @@
1
+ render_lab_tasks_posthog/__init__.py,sha256=fGcyw3Sxjue9wB_1RdFbEFKm5DXSlw_6vD2ud03a6og,58
2
+ render_lab_tasks_posthog/_app.py,sha256=nkWSD_6eq3xzdPJ_G7z6d5mv8tSB-Rq21yp07usJihA,48
3
+ render_lab_tasks_posthog/await_export.py,sha256=P8TTBUKUtx9R--lm5hkbyWvyjjIdcdOgdTWxDs0kA4w,620
4
+ render_lab_tasks_posthog/await_query.py,sha256=Fyjxe_xxY36V6hoPGY8v3c7RU_ggM47LMgVsPQAD_Iw,607
5
+ render_lab_tasks_posthog/capture.py,sha256=hEagMHoFfp6lW7Nu-aFWcgrH_o2wxg6egSUxmWeeUZI,576
6
+ render_lab_tasks_posthog/capture_batch.py,sha256=XZZyBtnWnGOuzFF27bxDOjaHWe9xjoEVWVU2owL6xoI,620
7
+ render_lab_tasks_posthog/client.py,sha256=T9lUXQj5WrAMclxcqPCQ0CGm_sPmTTkJVXVhuaZRDac,14682
8
+ render_lab_tasks_posthog/create_annotation.py,sha256=nQ4qgsnol_QfaH1qNMtaiisEWFrfW3GvS42p6RXUsJU,646
9
+ render_lab_tasks_posthog/create_export.py,sha256=n3MuaQSer0ZnNH-MmNrCF6D6ZU4qQ6wdeZas8owSR0k,611
10
+ render_lab_tasks_posthog/create_feature_flag.py,sha256=jP6_vBDP5mveysShzA81V7XygRuwFSwe0uRJxhQSdS0,661
11
+ render_lab_tasks_posthog/evaluate_flags.py,sha256=tFribP8duuItnIzBZwpyD_ZP3vvXXSj-ul1iKEPR_-8,634
12
+ render_lab_tasks_posthog/group_identify.py,sha256=HGIPow9YnPlNJEZcsK0ncagQyJH_xJSLR-pyvTQQ8Qo,628
13
+ render_lab_tasks_posthog/identify.py,sha256=DuPotNm2IindAg4qTZzsm75dJVOWIMZqpluZQhV7ZxU,584
14
+ render_lab_tasks_posthog/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
15
+ render_lab_tasks_posthog/retry.py,sha256=BjKhXYifigKGxcxtOxUYo0x5QWskbvaTEKd-hF38ZnU,363
16
+ render_lab_tasks_posthog/run_query.py,sha256=dp3xqWJS2dBEH6VgBti-ccEgCyItrgFS_jujYSZJedE,576
17
+ render_lab_tasks_posthog/tasks.py,sha256=r-NxEcMvuJlTCYTgY6o2ATSRgGdmMdqVTes4hOt6FvM,1344
18
+ render_lab_tasks_posthog/types.py,sha256=JNdPSkPWYDTbRzS4yg5LQoL_JZ0PvQxe6WbG8PW62NU,3148
19
+ render_lab_tasks_posthog/update_feature_flag.py,sha256=E4-ddP7ETYEmx6QadefkjXfLMaBXnjKsVAmY9AQkVQk,655
20
+ render_lab_tasks_posthog-0.1.0.dist-info/METADATA,sha256=St2ItM4BWyysysESwco2wFgBztszI4YVHIVZPSkIe90,3726
21
+ render_lab_tasks_posthog-0.1.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
22
+ render_lab_tasks_posthog-0.1.0.dist-info/licenses/LICENSE,sha256=LvmsuKGkhvlSISJRqvBIPUQ_BqVDFRe0RghPSmDebzU,1067
23
+ render_lab_tasks_posthog-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Render Lab
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.