:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement cursor import source (#69609)
Tom Owers7b3bf8d418bd
diff --git a/frontend/public/services/cursor.svg b/frontend/public/services/cursor.svgnew file mode 100644index 000000000000..7a208ccb7b4a--- /dev/null+++ b/frontend/public/services/cursor.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" fill="none"><mask id="a" width="832" height="832" x="96" y="96" maskUnits="userSpaceOnUse" style="mask-type:luminance"><path fill="#fff" fillRule="evenodd" d="M808.825 109.876C767.549 96 740.643 96 644.764 96H379.231c-95.878 0-122.78 0-164.056 13.876-48.802 17.837-87.462 56.497-105.299 105.294C96 256.451 96 283.353 96 379.231v265.533c0 95.879 0 122.785 13.876 164.061 17.837 48.797 56.497 87.462 105.299 105.294C256.451 928 283.353 928 379.231 928h265.533c95.879 0 122.785 0 164.061-13.881 48.797-17.832 87.462-56.497 105.294-105.294C928 767.549 928 740.643 928 644.764V379.231c0-95.878 0-122.78-13.881-164.061-17.832-48.797-56.497-87.457-105.294-105.294" clipRule="evenodd" style="fill:#fff;fill-opacity:1"/></mask><g mask="url(#a)"><path fill="#23222F" d="M96 96h832v832H96z" style="fill:#23222f;fill:color(display-p3 .1357 .134 .186);fill-opacity:1"/><rect width="768" height="768" x="128" y="128" fill="url(#b)" rx="160" style="mix-blend-mode:luminosity"/><g filter="url(#c)" opacity=".7"><ellipse cx="512" cy="900.615" fill="#4FAAFF" rx="400" ry="384.615" style="fill:#4faaff;fill:color(display-p3 .3098 .6667 1);fill-opacity:1"/></g><g filter="url(#d)" opacity=".7" style="mix-blend-mode:overlay"><ellipse cx="476" cy="882" fill="#fff" rx="183" ry="72" style="fill:#fff;fill-opacity:1"/></g><g filter="url(#e)" opacity=".6" style="mix-blend-mode:luminosity"><ellipse cx="512" cy="96" fill="#B3B3B3" fill-opacity=".5" rx="284" ry="129" style="fill:#b3b3b3;fill:color(display-p3 .7 .7 .7);fill-opacity:.5"/></g><g filter="url(#f)" opacity=".2" style="mix-blend-mode:luminosity"><ellipse cx="512" cy="96" fill="#B3B3B3" fill-opacity=".5" rx="542" ry="246" style="fill:#b3b3b3;fill:color(display-p3 .7 .7 .7);fill-opacity:.5"/></g><g style="mix-blend-mode:color-burn"><rect width="768" height="768" x="128" y="128" fill="#4FAAFF" opacity=".2" rx="160" style="fill:#4faaff;fill:color(display-p3 .3098 .6667 1);fill-opacity:1"/></g><g filter="url(#g)" opacity=".8"><path fill="#000" fillRule="evenodd" d="M725.606 331.636c5.112-3.377 11.887.525 11.531 6.642l-31.313 538.204c-.401 6.892-9.157 9.571-13.346 4.083L537.777 677.88a7.45 7.45 0 0 0-4.931-2.861L280.45 641.283c-6.82-.911-8.857-9.795-3.116-13.587z" clipRule="evenodd" style="fill:#000;fill-opacity:1"/></g><g filter="url(#h)" opacity=".3"><path fill="#000" fillRule="evenodd" d="M632.268 407.006c5.113-3.382 11.892.52 11.536 6.639l-25.833 444.694c-.401 6.896-9.163 9.573-13.35 4.079l-126.959-166.59a7.44 7.44 0 0 0-4.932-2.865l-207.193-27.736c-6.816-.912-8.854-9.79-3.118-13.584z" clipRule="evenodd" style="fill:#000;fill-opacity:1"/></g><g filter="url(#i)"><path fill="#4FAAFF" fillRule="evenodd" d="M680.944 244.828c5.112-3.381 11.892-.41 11.536 5.709l-14.605 264.65-14.969 263.809c-.656 29.379-25.476 48.962-46.315 21.639-44.91-58.881-111-159-145-180.5s-150.246-31.958-224-38.5c-20-1.774-27-33-7.753-45.474z" clipRule="evenodd" style="fill:#4faaff;fill:color(display-p3 .3098 .6667 1);fill-opacity:1"/></g><path stroke="#130D20" stroke-opacity=".6" stroke-width="1.5" d="M681.358 245.454c2.341-1.549 5.036-1.627 7.083-.656 2.03.961 3.45 2.958 3.291 5.695v.002l-14.606 264.65v.001l-14.969 263.808v.012l-.001.013c-.324 14.519-6.618 26.469-15.215 31.451-4.28 2.48-9.145 3.248-14.203 1.763-5.072-1.49-10.407-5.269-15.551-12.013-11.221-14.711-23.766-32.001-36.81-50.005l-1.418-1.957c-12.603-17.397-25.64-35.391-38.36-52.302-13.197-17.544-26.062-33.931-37.76-47.282-11.683-13.335-22.249-23.695-30.848-29.133-8.609-5.444-22.351-10.151-39.195-14.26-16.864-4.115-36.914-7.646-58.191-10.708-42.554-6.123-90.074-10.374-126.948-13.645-9.57-.849-16.123-8.754-17.924-18.119-1.798-9.348 1.193-19.939 10.512-25.978l.006-.004z" style="stroke:#130d20;stroke:color(display-p3 .0761 .0503 .1247);stroke-opacity:.6;mix-blend-mode:soft-light"/><path fill="url(#j)" fill-opacity=".75" fillRule="evenodd" d="M680.944 244.828c5.112-3.381 11.892-.41 11.536 5.709l-14.605 264.65-14.969 263.809c-.656 29.379-25.476 48.962-46.315 21.639-44.91-58.881-111-159-145-180.5s-150.246-31.958-224-38.5c-20-1.774-27-33-7.753-45.474z" clipRule="evenodd" style="mix-blend-mode:multiply"/><mask id="k" width="465" height="571" x="228" y="243" maskUnits="userSpaceOnUse" style="mask-type:luminance"><path fill="#fff" fillRule="evenodd" d="M680.944 244.828c5.112-3.381 11.892-.41 11.536 5.709l-14.605 264.65-14.969 263.809c-.656 29.379-25.476 48.962-46.315 21.639-44.91-58.881-111-159-145-180.5s-150.246-31.958-224-38.5c-20-1.774-27-33-7.753-45.474z" clipRule="evenodd" style="fill:#fff;fill-opacity:1"/></mask><g mask="url(#k)"><g style="mix-blend-mode:overlay"><path fill="#000" fillRule="evenodd" d="M681.054 246.201c5.112-3.382 11.892.52 11.536 6.639l-30.783 529.892c-.832 14.332-19.599 19.462-27.639 7.568-40.254-59.551-117.96-170.955-148.401-190.037-30.407-19.06-165.524-30.387-237.415-35.17-14.357-.955-19.409-19.842-7.409-27.78z" clipRule="evenodd" opacity=".3" style="fill:#000;fill-opacity:1"/></g><g filter="url(#l)" style="mix-blend-mode:overlay"><circle cx="682.5" cy="833.5" r="45.5" fill="#fff" style="fill:#fff;fill-opacity:1"/></g><g filter="url(#m)" opacity=".9" style="mix-blend-mode:soft-light"><ellipse cx="558.861" cy="683.774" fill="#fff" rx="8" ry="88.852" style="fill:#fff;fill-opacity:1" transform="rotate(-37 558.861 683.774)"/></g><g filter="url(#n)" opacity=".5" style="mix-blend-mode:overlay"><ellipse cx="10.385" cy="104.25" fill="#fff" rx="10.385" ry="104.25" style="fill:#fff;fill-opacity:1" transform="scale(-1 1)rotate(82.5 -442.793 125.358)"/></g></g><mask id="o" width="459" height="553" x="235" y="242" maskUnits="userSpaceOnUse" style="mask-type:alpha"><path fill="#D8D8D8" fillRule="evenodd" d="M682.055 244.201c5.112-3.382 11.891.52 11.536 6.639l-30.783 529.892c-.833 14.332-19.6 19.462-27.639 7.568-40.255-59.551-117.96-170.956-148.402-190.037-30.407-19.06-165.524-30.387-237.415-35.17-14.356-.955-19.409-19.842-7.408-27.78z" clipRule="evenodd" style="fill:#d8d8d8;fill:color(display-p3 .847 .847 .847);fill-opacity:1"/></mask><g mask="url(#o)"><path fill="url(#p)" fillRule="evenodd" d="m694.453 236-34.265 589.819-173.421-227.556z" clipRule="evenodd"/><path fill="url(#q)" fillRule="evenodd" d="M694.453 236 486.767 598.263 204 560.411z" clipRule="evenodd"/><g filter="url(#r)" opacity=".7"><path fill="url(#s)" fillRule="evenodd" d="M613.558 375.123 550.73 674.92l-57.648-76.987-104.66-34.887z" clipRule="evenodd"/></g><g filter="url(#t)"><path fill="#fff" fill-opacity=".2" fillRule="evenodd" d="M682.054 244.201c5.112-3.382 11.892.52 11.536 6.639l-30.783 529.892c-.832 14.332-19.599 19.462-27.639 7.568-40.254-59.551-117.96-170.955-148.401-190.037-30.407-19.06-165.524-30.387-237.415-35.17-14.357-.955-19.409-19.842-7.409-27.78z" clipRule="evenodd" style="fill:#fff;fill-opacity:.2;mix-blend-mode:soft-light"/></g><path stroke="url(#u)" stroke-width="1.5" d="M682.468 244.826c4.597-3.04 10.693.468 10.374 5.97l-30.783 529.893c-.791 13.612-18.63 18.493-26.27 7.191-20.129-29.779-49.627-72.53-77.902-110.225-14.136-18.846-27.973-36.437-40.184-50.514-12.192-14.054-22.821-24.676-30.538-29.513-7.728-4.844-21.997-9.147-40.058-12.962-18.095-3.823-40.106-7.179-63.398-10.086-46.588-5.815-98.357-9.843-134.307-12.235-13.647-.908-18.442-18.868-7.045-26.406z"/><path fill="url(#v)" d="m310.521 501.14 366.543-245.603-74.425 100.009c-27.774 37.935-77.172 60.604-128.848 74.89-54.777 15.143-132.873 80.038-163.27 70.704"/></g><g fill="#fff" opacity=".6" style="mix-blend-mode:overlay"><mask id="w"><path fillRule="evenodd" d="M808.825 109.876C767.549 96 740.643 96 644.764 96H379.231c-95.878 0-122.78 0-164.056 13.876-48.802 17.837-87.462 56.497-105.299 105.294C96 256.451 96 283.353 96 379.231v265.533c0 95.879 0 122.785 13.876 164.061 17.837 48.797 56.497 87.462 105.299 105.294C256.451 928 283.353 928 379.231 928h265.533c95.879 0 122.785 0 164.061-13.881 48.797-17.832 87.462-56.497 105.294-105.294C928 767.549 928 740.643 928 644.764V379.231c0-95.878 0-122.78-13.881-164.061-17.832-48.797-56.497-87.457-105.294-105.294" clipRule="evenodd"/></mask><path d="m215.175 109.876-10.197-30.332-.396.133-.393.144zM109.876 215.17l-30.055-10.986-.144.393-.133.397zm0 593.655-30.332 10.197.133.397.144.393zm105.299 105.294-10.983 30.057.39.142.393.132zm593.65 0 10.2 30.331.394-.132.39-.143zm105.294-105.294 30.056 10.984.143-.39.132-.394zm0-593.655 30.332-10.199-.133-.394-.143-.391zM819.022 79.544C771.797 63.668 739.18 64 644.764 64v64c97.342 0 118.537.332 153.865 12.208zM644.764 64H379.231v64h265.533zm-265.533 0c-94.416 0-127.028-.332-174.253 15.544l20.393 60.664C260.7 128.332 281.89 128 379.231 128zM204.189 79.82c-57.656 21.074-103.294 66.712-124.368 124.364l60.11 21.972c14.6-39.941 46.283-71.624 86.229-86.225zM79.544 204.975C63.669 252.203 64 284.815 64 379.231h64c0-97.341.332-118.532 12.208-153.865zM64 379.231v265.533h64V379.231zm0 265.533c0 94.416-.332 127.033 15.544 174.258l60.664-20.393C128.332 763.301 128 742.106 128 644.764zm15.82 175.048c21.074 57.65 66.711 103.294 124.372 124.364l21.966-60.113c-39.943-14.595-71.626-46.281-86.227-86.224zM204.976 944.45c47.225 15.882 79.84 15.55 174.255 15.55v-64c-97.342 0-118.53-.332-153.856-12.211zM379.231 960h265.533v-64H379.231zm265.533 0c94.415 0 127.034.332 174.261-15.55l-20.4-60.661C763.299 895.668 742.106 896 644.764 896zm175.045-15.825c57.654-21.069 103.297-66.712 124.366-124.366l-60.111-21.968c-14.596 39.94-46.283 71.627-86.223 86.223zm124.641-125.15C960.332 771.798 960 739.179 960 644.764h-64c0 97.342-.332 118.535-12.211 153.861zM960 644.764V379.231h-64v265.533zm0-265.533c0-94.416.332-127.029-15.549-174.26l-60.663 20.398C895.668 260.701 896 281.89 896 379.231zm-15.825-175.045c-21.07-57.655-66.713-103.292-124.363-124.365l-21.973 60.11c39.944 14.601 71.629 46.285 86.225 86.223z" mask="url(#w)" style="fill:#fff;fill-opacity:1"/></g></g><defs><filter id="c" width="1408.99" height="1378.22" x="-192.493" y="211.507" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_28_9" stdDeviation="152.247"/></filter><filter id="d" width="686" height="464" x="133" y="650" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_28_9" stdDeviation="80"/></filter><filter id="e" width="888" height="578" x="68" y="-193" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_28_9" stdDeviation="80"/></filter><filter id="f" width="1444" height="852" x="-210" y="-330" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_28_9" stdDeviation="90"/></filter><filter id="g" width="693.882" height="783.832" x="158.628" y="215.029" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_28_9" stdDeviation="57.679"/></filter><filter id="h" width="496.38" height="571.243" x="203.257" y="349.937" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_28_9" stdDeviation="27.909"/></filter><filter id="i" width="464.007" height="570.287" x="228.487" y="243.411" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feColorMatrix in="SourceAlpha" result="hardAlpha" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"/><feOffset/><feGaussianBlur stdDeviation="6"/><feComposite in2="hardAlpha" k2="-1" k3="1" operator="arithmetic"/><feColorMatrix values="0 0 0 0 0.309804 0 0 0 0 0.666667 0 0 0 0 1 0 0 0 1 0"/><feBlend in2="shape" mode="soft-light" result="effect1_innerShadow_28_9"/></filter><filter id="l" width="115" height="115" x="625" y="776" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_28_9" stdDeviation="6"/></filter><filter id="m" width="131.716" height="166.252" x="493.003" y="600.648" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_28_9" stdDeviation="6"/></filter><filter id="n" width="230.735" height="58.13" x="247.346" y="542.839" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_28_9" stdDeviation="6"/></filter><filter id="r" width="344.216" height="418.877" x="328.882" y="315.583" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_28_9" stdDeviation="29.77"/></filter><filter id="t" width="458.38" height="551.963" x="235.223" y="242.951" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feColorMatrix in="SourceAlpha" result="hardAlpha" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"/><feOffset/><feGaussianBlur stdDeviation="32"/><feComposite in2="hardAlpha" k2="-1" k3="1" operator="arithmetic"/><feColorMatrix values="0 0 0 0 0.233594 0 0 0 0 0.253455 0 0 0 0 0.308073 0 0 0 0.25 0"/><feBlend in2="shape" mode="soft-light" result="effect1_innerShadow_28_9"/></filter><linearGradient id="j" x1="237.5" x2="666" y1="537" y2="780.5" gradientUnits="userSpaceOnUse"><stop stop-color="#1A1A1A" style="stop-color:#1a1a1a;stop-color:color(display-p3 .1 .1 .1);stop-opacity:1"/><stop offset=".034" stop-color="#BFBFBF" style="stop-color:#bfbfbf;stop-color:color(display-p3 .75 .75 .75);stop-opacity:1"/><stop offset=".079" stop-color="gray" style="stop-color:gray;stop-color:color(display-p3 .5 .5 .5);stop-opacity:1"/><stop offset=".498" stop-color="#4D4D4D" style="stop-color:#4d4d4d;stop-color:color(display-p3 .3 .3 .3);stop-opacity:1"/><stop offset=".504" stop-color="#999" style="stop-color:#999;stop-color:color(display-p3 .6 .6 .6);stop-opacity:1"/><stop offset=".955" stop-color="#E6E6E6" style="stop-color:#e6e6e6;stop-color:color(display-p3 .9 .9 .9);stop-opacity:1"/><stop offset="1" stop-color="#333" style="stop-color:#333;stop-color:color(display-p3 .2 .2 .2);stop-opacity:1"/></linearGradient><linearGradient id="p" x1="694.275" x2="564.032" y1="236" y2="696.505" gradientUnits="userSpaceOnUse"><stop stop-color="#A7AEB6" style="stop-color:#a7aeb6;stop-color:color(display-p3 .653 .6833 .7137);stop-opacity:1"/><stop offset="1" stop-color="#A4B1BF" style="stop-color:#a4b1bf;stop-color:color(display-p3 .6426 .6958 .7491);stop-opacity:1"/></linearGradient><linearGradient id="q" x1="694.276" x2="342.617" y1="236" y2="577.426" gradientUnits="userSpaceOnUse"><stop stop-color="#F7FAFB" style="stop-color:#f7fafb;stop-color:color(display-p3 .9672 .9814 .9828);stop-opacity:1"/><stop offset=".542" stop-color="#ECEEED" style="stop-color:#eceeed;stop-color:color(display-p3 .9252 .9345 .9289);stop-opacity:1"/><stop offset="1" stop-color="#DEDFE2" style="stop-color:#dedfe2;stop-color:color(display-p3 .8706 .8738 .8877);stop-opacity:1"/></linearGradient><linearGradient id="s" x1="409.595" x2="610.132" y1="506.325" y2="595.788" gradientUnits="userSpaceOnUse"><stop stop-color="#BAB8C2" style="stop-color:#bab8c2;stop-color:color(display-p3 .7294 .7216 .7608);stop-opacity:1"/><stop offset="1" stop-color="#E5E5E7" style="stop-color:#e5e5e7;stop-color:color(display-p3 .898 .898 .9059);stop-opacity:1"/></linearGradient><linearGradient id="u" x1="682" x2="441" y1="252" y2="681" gradientUnits="userSpaceOnUse"><stop stop-color="#13111D" style="stop-color:#13111d;stop-color:color(display-p3 .0753 .0684 .115);stop-opacity:1"/><stop offset="1" stop-color="#575562" stop-opacity=".21" style="stop-color:#575562;stop-color:color(display-p3 .3405 .333 .3837);stop-opacity:.21"/></linearGradient><linearGradient id="v" x1="687.763" x2="367.735" y1="236.465" y2="506.256" gradientUnits="userSpaceOnUse"><stop stop-color="#fff" style="stop-color:white;stop-opacity:1"/><stop offset=".954" stop-color="#fff" stop-opacity="0" style="stop-color:none;stop-opacity:0"/></linearGradient><radialGradient id="b" cx="0" cy="0" r="1" gradientTransform="rotate(180 256 256)scale(423)" gradientUnits="userSpaceOnUse"><stop style="stop-color:black;stop-opacity:1"/><stop offset="1" stop-opacity="0" style="stop-color:none;stop-opacity:0"/></radialGradient></defs></svg>\ No newline at end of filediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 37497a78a2d6..ebaa4bac7cde 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -126,6 +126,7 @@ the row lists both.| coupa | HTTP | requests | ✅ || crunchbase | HTTP | requests | ✅ || culture_amp | HTTP | requests | ✅ |+| cursor | HTTP | requests | ✅ || customer_io | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (App API) / ➖ (webhook) || datadog | HTTP | requests | ✅ || decagon | HTTP | requests | ✅ |@@ -499,7 +500,6 @@ doesn't conflict with concurrent PRs.- cosmosdb- couchbase- criteo-- cursor- curve- customerly- databricksdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/canonical_descriptions.pynew file mode 100644index 000000000000..b74cd9ede22e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/canonical_descriptions.py@@ -0,0 +1,85 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "members": {+ "description": "Current members of your Cursor team with their roles.",+ "docs_url": "https://cursor.com/docs/account/teams/admin-api",+ "columns": {+ "id": "Unique numeric identifier for the team member.",+ "email": "Email address of the team member.",+ "name": "Display name of the team member.",+ "role": "Role of the member within the team (e.g. owner, member).",+ "isRemoved": "Whether the member has been removed from the team.",+ },+ },+ "daily_usage": {+ "description": "Per-user daily Cursor usage metrics: lines of code, tab completions, agent/chat requests, and most-used models.",+ "docs_url": "https://cursor.com/docs/account/teams/admin-api",+ "columns": {+ "userId": "Unique numeric identifier for the user.",+ "date": "Day the metrics are aggregated for.",+ "email": "Email address of the user.",+ "isActive": "Whether the user was active on this day.",+ "totalLinesAdded": "Total lines of code added by the user on this day.",+ "totalLinesDeleted": "Total lines of code deleted by the user on this day.",+ "acceptedLinesAdded": "Lines added from AI suggestions the user accepted.",+ "acceptedLinesDeleted": "Lines deleted from AI suggestions the user accepted.",+ "totalApplies": "Number of times the user applied AI-suggested changes.",+ "totalAccepts": "Number of AI suggestions the user accepted.",+ "totalRejects": "Number of AI suggestions the user rejected.",+ "totalTabsShown": "Number of tab completions shown to the user.",+ "totalTabsAccepted": "Number of tab completions the user accepted.",+ "composerRequests": "Number of composer requests made by the user.",+ "chatRequests": "Number of chat requests made by the user.",+ "agentRequests": "Number of agent requests made by the user.",+ "cmdkUsages": "Number of Cmd+K uses by the user.",+ "subscriptionIncludedReqs": "Requests covered by the subscription's included quota.",+ "apiKeyReqs": "Requests made using the user's own API key.",+ "usageBasedReqs": "Requests billed as usage-based pricing.",+ "bugbotUsages": "Number of Bugbot uses by the user.",+ "mostUsedModel": "The model the user used most on this day.",+ "applyMostUsedExtension": "File extension most often involved in applied changes.",+ "tabMostUsedExtension": "File extension most often involved in tab completions.",+ "clientVersion": "Version of the Cursor client the user was on.",+ },+ },+ "usage_events": {+ "description": "Individual Cursor usage events with the model used, token usage, and cost charged.",+ "docs_url": "https://cursor.com/docs/account/teams/admin-api",+ "columns": {+ "id": "Synthetic identifier computed by PostHog from the event payload (the API does not return an event ID).",+ "timestamp": "When the usage event occurred.",+ "userEmail": "Email address of the user who triggered the event.",+ "model": "Model used for the request.",+ "kind": "Kind of usage event (e.g. chat, agent, tab).",+ "maxMode": "Whether Max mode was enabled for the request.",+ "requestsCosts": "Cost of the request in request units.",+ "isTokenBasedCall": "Whether the request was billed on token usage.",+ "isChargeable": "Whether the event is chargeable.",+ "isHeadless": "Whether the event came from a headless (non-editor) context.",+ "tokenUsage": "Token usage breakdown: input, output, cache write, and cache read tokens, plus total cost in cents.",+ "chargedCents": "Amount charged for the request, in cents.",+ "cursorTokenFee": "Cursor's token fee for eligible third-party model requests, when applicable.",+ "serviceAccountId": "Identifier of the service account, for service-account events.",+ "serviceAccountName": "Name of the service account, for service-account events.",+ },+ },+ "spend": {+ "description": "Per-member spend for the current billing cycle.",+ "docs_url": "https://cursor.com/docs/account/teams/admin-api",+ "columns": {+ "userId": "Unique numeric identifier for the team member.",+ "name": "Display name of the team member.",+ "email": "Email address of the team member.",+ "role": "Role of the member within the team.",+ "spendCents": "On-demand (usage-based) spend in the current billing cycle, in cents.",+ "overallSpendCents": "Total spend including subscription-included usage, in cents.",+ "fastPremiumRequests": "Number of fast premium requests used in the current billing cycle.",+ "hardLimitOverrideDollars": "Per-member hard spend limit override in dollars (0 means no override).",+ "monthlyLimitDollars": "Per-member monthly spend limit in dollars, when set.",+ "subscriptionCycleStart": "Start of the current subscription billing cycle (epoch milliseconds).",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/cursor.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/cursor.pynew file mode 100644index 000000000000..fcaf9dd466c6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/cursor.py@@ -0,0 +1,339 @@+import base64+import hashlib+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any++import orjson+import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from urllib3.util.retry import Retry++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.cursor.settings import (+ CURSOR_ENDPOINTS,+ CursorEndpointConfig,+)++CURSOR_BASE_URL = "https://api.cursor.com"++# The windowed endpoints reject date ranges longer than 30 days, so backfills chunk into windows.+MAX_WINDOW_DAYS = 30+# First sync fetches this much history instead of walking back to the team's creation.+DEFAULT_LOOKBACK_DAYS = 365+REQUEST_TIMEOUT_SECONDS = 60+++class CursorRetryableError(Exception):+ pass+++class CursorResumeConfig:+ # Start (epoch ms) of the window being processed when the sync was interrupted.+ # None for the non-windowed endpoints (members, spend).+ window_start: int | None = None+ # 1-based page to resume from within that window (or within the spend listing).+ page: int = 1+++def _to_epoch_ms(value: Any) -> int:+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return int(aware.timestamp() * 1000)+ if isinstance(value, date):+ return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp() * 1000)+ if isinstance(value, int | float):+ return int(value)+ return int(str(value))+++def _from_epoch_ms(value: Any) -> datetime:+ return datetime.fromtimestamp(int(value) / 1000, tz=UTC)+++def _now_ms() -> int:+ return int(datetime.now(UTC).timestamp() * 1000)+++def _basic_token(api_key: str) -> str:+ # Cursor's Admin API uses HTTP Basic auth with the API key as the username and an empty password.+ return base64.b64encode(f"{api_key}:".encode("ascii")).decode("ascii")+++def _redact_values(api_key: str) -> tuple[str, ...]:+ # Mask both the raw key and the derived Basic token so neither leaks into logged URLs/samples.+ return (api_key, _basic_token(api_key))+++def _make_session(api_key: str) -> requests.Session:+ # Redirects are pinned off so the credential can't be replayed to a cross-host redirect target;+ # urllib3 retries are disabled so tenacity (on `_fetch`) is the single retry layer.+ return make_tracked_session(+ headers={"Authorization": f"Basic {_basic_token(api_key)}", "Accept": "application/json"},+ redact_values=_redact_values(api_key),+ allow_redirects=False,+ retry=Retry(total=0),+ )+++@retry(+ retry=retry_if_exception_type(+ (+ CursorRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(6),+ # The main read endpoints are limited to ~20 requests/minute per team, so back off far enough+ # for the rate-limit window to reset before giving up.+ wait=wait_exponential_jitter(initial=3, max=70),+ reraise=True,+)+def _fetch(+ session: requests.Session,+ method: str,+ url: str,+ logger: FilteringBoundLogger,+ json_body: dict[str, Any] | None = None,+) -> dict[str, Any]:+ response = session.request(+ method,+ url,+ json=json_body,+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise CursorRetryableError(f"Cursor API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Cursor API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def validate_credentials(api_key: str) -> bool:+ try:+ response = _make_session(api_key).get(f"{CURSOR_BASE_URL}/teams/members", timeout=10)+ return response.status_code == 200+ except Exception:+ return False+++def _usage_event_id(item: dict[str, Any]) -> str:+ """Deterministic id for a usage event, hashed from the raw payload.++ The filtered-usage-events endpoint returns no event identifier, so this synthesizes one:+ identical payloads (the same event re-fetched across overlapping incremental windows)+ collapse to one row on merge, while any field difference yields a distinct key. Two+ genuinely identical events in the same millisecond would collapse too — an accepted+ tradeoff versus unbounded duplication.+ """+ return hashlib.sha256(orjson.dumps(item, option=orjson.OPT_SORT_KEYS)).hexdigest()+++def _normalize_daily_usage(item: dict[str, Any]) -> dict[str, Any]:+ if "date" in item and item["date"] is not None:+ item["date"] = _from_epoch_ms(item["date"])+ return item+++def _normalize_usage_event(item: dict[str, Any]) -> dict[str, Any]:+ item["id"] = _usage_event_id(item)+ # `timestamp` arrives as an epoch-ms string; convert so the column is a real datetime.+ if "timestamp" in item and item["timestamp"] is not None:+ item["timestamp"] = _from_epoch_ms(item["timestamp"])+ return item+++def _build_windows(start_ms: int, end_ms: int) -> Iterator[tuple[int, int]]:+ """Chunk [start_ms, end_ms] into inclusive windows of at most MAX_WINDOW_DAYS."""+ window_ms = int(timedelta(days=MAX_WINDOW_DAYS).total_seconds() * 1000)+ window_start = start_ms+ while window_start <= end_ms:+ window_end = min(window_start + window_ms - 1, end_ms)+ yield window_start, window_end+ window_start = window_end + 1+++def _has_next_page(data: dict[str, Any], page: int, items_count: int, page_size: int) -> bool:+ """Read the has-more signal from whichever pagination shape the endpoint returns.++ filtered-usage-events and daily-usage-data nest `hasNextPage` (plus `numPages`/`totalPages`)+ under `pagination`; /teams/spend returns `totalPages` at the top level. Fall back to a+ full-page heuristic when neither is present (the API silently ignoring pagination params+ would otherwise loop forever on the same rows).+ """+ pagination = data.get("pagination")+ if isinstance(pagination, dict):+ has_next = pagination.get("hasNextPage")+ if has_next is not None:+ return bool(has_next)+ total_pages = pagination.get("numPages") or pagination.get("totalPages")+ if total_pages is not None:+ return page < int(total_pages)+ total_pages = data.get("totalPages")+ if total_pages is not None:+ return page < int(total_pages)+ return items_count >= page_size+++def _get_members_rows(+ session: requests.Session,+ config: CursorEndpointConfig,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ data = _fetch(session, config.method, f"{CURSOR_BASE_URL}{config.path}", logger)+ rows = data.get(config.data_key) or []+ if rows:+ yield rows+++def _get_spend_rows(+ session: requests.Session,+ config: CursorEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CursorResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.page if resume is not None else 1++ while True:+ body = {+ "page": page,+ "pageSize": config.page_size,+ # Spend amounts change while we paginate; sorting by user keeps page boundaries stable.+ "sortBy": "user",+ "sortDirection": "asc",+ }+ data = _fetch(session, config.method, f"{CURSOR_BASE_URL}{config.path}", logger, json_body=body)++ rows = data.get(config.data_key) or []+ cycle_start = data.get("subscriptionCycleStart")+ for row in rows:+ row["subscriptionCycleStart"] = cycle_start++ has_next = _has_next_page(data, page, len(rows), config.page_size)++ if rows:+ yield rows+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it —+ # merge dedupes on the primary key.+ if has_next:+ resumable_source_manager.save_state(CursorResumeConfig(page=page + 1))++ if not rows or not has_next:+ break+ page += 1+++def _get_windowed_rows(+ session: requests.Session,+ config: CursorEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CursorResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ end_ms = _now_ms()++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.window_start is not None:+ start_ms = resume.window_start+ first_window_page = resume.page+ logger.debug(f"Cursor: resuming {config.name} from window_start={start_ms}, page={first_window_page}")+ else:+ if should_use_incremental_field and db_incremental_field_last_value is not None:+ # startDate/endDate bounds are inclusive, so starting at the watermark re-fetches the+ # rows at exactly the watermark value — merge dedupes them, and for daily_usage it also+ # refreshes the partial day the previous sync ended on.+ start_ms = min(_to_epoch_ms(db_incremental_field_last_value), end_ms)+ else:+ start_ms = end_ms - int(timedelta(days=DEFAULT_LOOKBACK_DAYS).total_seconds() * 1000)+ first_window_page = 1++ if config.name == "usage_events":+ normalize = _normalize_usage_event+ elif config.name == "daily_usage":+ normalize = _normalize_daily_usage+ else:+ raise ValueError(f"No normalizer defined for windowed endpoint: {config.name}")++ for window_start, window_end in _build_windows(start_ms, end_ms):+ page = first_window_page+ first_window_page = 1 # only the resumed-into window starts mid-pagination++ while True:+ body = {+ "startDate": window_start,+ "endDate": window_end,+ "page": page,+ "pageSize": config.page_size,+ }+ data = _fetch(session, config.method, f"{CURSOR_BASE_URL}{config.path}", logger, json_body=body)++ items = data.get(config.data_key) or []+ rows = [normalize(item) for item in items]+ has_next = _has_next_page(data, page, len(items), config.page_size)++ if rows:+ yield rows+ # Save AFTER yielding so a crash re-yields the last batch rather than skipping it.+ if has_next:+ resumable_source_manager.save_state(CursorResumeConfig(window_start=window_start, page=page + 1))+ else:+ next_window = window_end + 1+ if next_window <= end_ms:+ resumable_source_manager.save_state(CursorResumeConfig(window_start=next_window, page=1))++ if not items or not has_next:+ break+ page += 1+++def cursor_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CursorResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> SourceResponse:+ config = CURSOR_ENDPOINTS.get(endpoint)+ if config is None:+ raise ValueError(f"Unknown Cursor endpoint: {endpoint}")++ def get_rows() -> Iterator[list[dict[str, Any]]]:+ session = _make_session(api_key)++ if endpoint == "members":+ yield from _get_members_rows(session, config, logger)+ elif endpoint == "spend":+ yield from _get_spend_rows(session, config, logger, resumable_source_manager)+ else:+ yield from _get_windowed_rows(+ session,+ config,+ logger,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )++ return SourceResponse(+ name=endpoint,+ items=get_rows,+ primary_keys=config.primary_keys,+ partition_keys=[config.partition_key] if config.partition_key else None,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ sort_mode="asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/settings.pynew file mode 100644index 000000000000..f74543ae5f4c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/settings.py@@ -0,0 +1,85 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class CursorEndpointConfig:+ name: str+ path: str+ method: Literal["GET", "POST"] = "POST"+ data_key: str = "data" # Response key holding the list of rows+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Endpoint takes startDate/endDate epoch-ms body params with a 30-day max range,+ # so syncs chunk the requested range into windows.+ windowed: bool = False+ paginated: bool = True+ page_size: int = 100+ partition_key: Optional[str] = None # Stable datetime field to partition by+ description: Optional[str] = None+ should_sync_default: bool = True+++CURSOR_ENDPOINTS: dict[str, CursorEndpointConfig] = {+ "members": CursorEndpointConfig(+ name="members",+ path="/teams/members",+ method="GET",+ data_key="teamMembers",+ primary_keys=["id"],+ paginated=False,+ description="Current team members with their roles. Full refresh only",+ ),+ "daily_usage": CursorEndpointConfig(+ name="daily_usage",+ path="/teams/daily-usage-data",+ data_key="data",+ # One row per team member per day.+ primary_keys=["date", "userId"],+ windowed=True,+ partition_key="date",+ incremental_fields=[+ {+ "label": "date",+ "type": IncrementalFieldType.DateTime,+ "field": "date",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ description="Per-user daily usage metrics (lines accepted, tabs, agent requests). Only syncs the last 365 days on initial sync",+ ),+ "usage_events": CursorEndpointConfig(+ name="usage_events",+ path="/teams/filtered-usage-events",+ data_key="usageEvents",+ # The API returns no event identifier, so `id` is synthesized in cursor.py from a+ # hash of the raw event payload — identical payloads dedupe, distinct ones never collide.+ primary_keys=["id"],+ windowed=True,+ partition_key="timestamp",+ incremental_fields=[+ {+ "label": "timestamp",+ "type": IncrementalFieldType.DateTime,+ "field": "timestamp",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ description="Per-request usage events with model, token usage, and cost. Only syncs the last 365 days on initial sync",+ ),+ "spend": CursorEndpointConfig(+ name="spend",+ path="/teams/spend",+ data_key="teamMemberSpend",+ primary_keys=["userId"],+ description="Per-member spend for the current billing cycle. Full refresh only",+ ),+}++ENDPOINTS = tuple(CURSOR_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in CURSOR_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/source.pyindex 6eee670d1fa5..da95eb85ce20 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/source.py@@ -1,19 +1,44 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.cursor.cursor import (+ CURSOR_BASE_URL,+ CursorResumeConfig,+ cursor_source,+ validate_credentials as validate_cursor_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cursor.settings import (+ CURSOR_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CursorSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class CursorSource(SimpleSource[CursorSourceConfig]):+class CursorSource(ResumableSource[CursorSourceConfig, CursorResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CURSOR@@ -24,8 +49,96 @@ class CursorSource(SimpleSource[CursorSourceConfig]):name=SchemaExternalDataSourceType.CURSOR,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Cursor",- iconPath="/static/services/cursor.png",- keywords=["ai", "code editor", "developer tools", "usage"],- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Cursor Admin API key to automatically pull your team's Cursor usage and spend data into the PostHog Data warehouse.++You need a Cursor team plan (Business or Enterprise). A team admin can create an API key in the [Cursor dashboard](https://cursor.com/dashboard) under Settings → Cursor Admin API Keys.+""",+ iconPath="/static/services/cursor.svg",+ docsUrl="https://posthog.com/docs/cdp/sources/cursor",+ keywords=["ai", "code editor", "developer tools", "usage", "anysphere"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="Admin API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="key_...",+ secret=True,+ ),+ ],+ ),unreleasedSource=True,)++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.cursor.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid or revoked Admin API key surfaces as a requests HTTPError when `_fetch`+ # calls `raise_for_status()`. Retrying can never satisfy a credential problem, so stop+ # the sync. Match the stable status text and base host, not the per-request path.+ f"401 Client Error: Unauthorized for url: {CURSOR_BASE_URL}": "Your Cursor Admin API key is invalid or has been revoked. Create a new key in your Cursor dashboard settings, then reconnect.",+ f"403 Client Error: Forbidden for url: {CURSOR_BASE_URL}": "Your Cursor Admin API key does not have access to this data. Admin API keys must be created by a team admin, and some endpoints require an Enterprise plan.",+ }++ def get_schemas(+ self,+ config: CursorSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = CURSOR_ENDPOINTS[endpoint]+ has_incremental = len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental,+ supports_append=has_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ description=endpoint_config.description,+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: CursorSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_cursor_credentials(config.api_key):+ return True, None++ return False, "Invalid Cursor Admin API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CursorResumeConfig]:+ return ResumableSourceManager[CursorResumeConfig](inputs, CursorResumeConfig)++ def source_for_pipeline(+ self,+ config: CursorSourceConfig,+ resumable_source_manager: ResumableSourceManager[CursorResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return cursor_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/tests/test_cursor.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/tests/test_cursor.pynew file mode 100644index 000000000000..aef9d31e0bd0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/tests/test_cursor.py@@ -0,0 +1,350 @@+import base64+from collections.abc import Iterable, Iterator+from datetime import UTC, datetime+from typing import Any, cast++import pytest+from unittest import mock++import requests+from parameterized import parameterized+from tenacity import wait_none++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.cursor import cursor+from products.warehouse_sources.backend.temporal.data_imports.sources.cursor.cursor import (+ CursorResumeConfig,+ _build_windows,+ _has_next_page,+ _normalize_daily_usage,+ _normalize_usage_event,+ _usage_event_id,+ cursor_source,+ validate_credentials,+)++DAY_MS = 24 * 60 * 60 * 1000+WINDOW_MS = cursor.MAX_WINDOW_DAYS * DAY_MS++[email protected](autouse=True)+def _instant_retries():+ fetch: Any = cursor._fetch # the tenacity wrapper's `retry` attribute isn't in the Callable type+ original_wait = fetch.retry.wait+ fetch.retry.wait = wait_none()+ yield+ fetch.retry.wait = original_wait+++def _response(status_code: int = 200, json_data: dict | None = None) -> requests.Response:+ response = mock.Mock(spec=requests.Response)+ response.status_code = status_code+ response.ok = status_code < 400+ response.text = ""+ response.json.return_value = json_data or {}+ typed = cast(requests.Response, response)+ if status_code >= 400:+ response.raise_for_status.side_effect = requests.HTTPError(+ f"{status_code} Client Error: Error for url: {cursor.CURSOR_BASE_URL}/x", response=typed+ )+ return typed+++def _manager(resume_state: CursorResumeConfig | None = None) -> mock.Mock:+ manager = mock.Mock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _batches(source: SourceResponse) -> Iterator[list[dict[str, Any]]]:+ return iter(cast(Iterable[list[dict[str, Any]]], source.items()))+++class TestCursorTransport:+ @parameterized.expand(+ [+ (10, 1), # under one window+ (30, 1), # exactly one window+ (31, 2),+ (90, 3),+ ]+ )+ def test_build_windows_chunks_to_max_window(self, start_offset_days, expected_windows):+ end_ms = 1_700_000_000_000+ start_ms = end_ms - start_offset_days * DAY_MS + 1++ windows = list(_build_windows(start_ms, end_ms))++ assert len(windows) == expected_windows+ assert windows[0][0] == start_ms+ assert windows[-1][1] == end_ms+ for (_, prev_end), (next_start, _) in zip(windows, windows[1:]):+ assert next_start == prev_end + 1 # inclusive bounds — no gap, no overlap+ assert all(end - start < WINDOW_MS for start, end in windows)++ def test_usage_event_id_is_deterministic_and_distinct(self):+ event = {"timestamp": "1700000000000", "userEmail": "[email protected]", "model": "gpt-5"}++ assert _usage_event_id(dict(event)) == _usage_event_id({k: event[k] for k in reversed(list(event))})+ assert _usage_event_id(event) != _usage_event_id({**event, "model": "other"})++ def test_normalize_usage_event_adds_id_and_parses_timestamp(self):+ item = _normalize_usage_event({"timestamp": "1700000000000", "userEmail": "[email protected]"})++ assert item["timestamp"] == datetime.fromtimestamp(1_700_000_000, tz=UTC)+ assert isinstance(item["id"], str) and len(item["id"]) == 64++ def test_normalize_daily_usage_parses_date(self):+ item = _normalize_daily_usage({"date": 1_700_000_000_000, "userId": 1})++ assert item["date"] == datetime.fromtimestamp(1_700_000_000, tz=UTC)++ @parameterized.expand(+ [+ ({"pagination": {"hasNextPage": True}}, 1, 100, True),+ ({"pagination": {"hasNextPage": False}}, 1, 100, False),+ ({"pagination": {"numPages": 3}}, 2, 100, True),+ ({"pagination": {"numPages": 3}}, 3, 100, False),+ ({"pagination": {"totalPages": 2}}, 1, 100, True),+ ({"totalPages": 2}, 1, 100, True), # /teams/spend keeps totalPages at the top level+ ({"totalPages": 2}, 2, 100, False),+ ({}, 1, 100, True), # no pagination info — full page implies more+ ({}, 1, 50, False), # partial page implies done+ ]+ )+ def test_has_next_page_across_response_shapes(self, data, page, items_count, expected):+ assert _has_next_page(data, page, items_count, 100) is expected++ @parameterized.expand([(200, True), (401, False), (403, False)])+ def test_validate_credentials_maps_status(self, status_code, expected):+ session = mock.Mock()+ session.get.return_value = _response(status_code)++ with mock.patch.object(cursor, "make_tracked_session", return_value=session):+ assert validate_credentials("key_test") is expected++ def test_validate_credentials_false_on_connection_error(self):+ session = mock.Mock()+ session.get.side_effect = requests.ConnectionError("boom")++ with mock.patch.object(cursor, "make_tracked_session", return_value=session):+ assert validate_credentials("key_test") is False++ def test_session_masks_credentials_and_sends_basic_auth(self):+ # The tracked transport logs and samples requests; without redaction the raw key and the+ # derived Basic token would leak into HTTP telemetry.+ expected_token = base64.b64encode(b"key_test:").decode("ascii")++ with mock.patch.object(cursor, "make_tracked_session") as make_session:+ cursor._make_session("key_test")++ kwargs = make_session.call_args.kwargs+ assert kwargs["headers"]["Authorization"] == f"Basic {expected_token}"+ assert "key_test" in kwargs["redact_values"]+ assert expected_token in kwargs["redact_values"]+ assert kwargs["allow_redirects"] is False++ @parameterized.expand([(429,), (500,), (503,)])+ def test_fetch_retries_transient_errors(self, status_code):+ session = mock.Mock()+ session.request.side_effect = [_response(status_code), _response(200, {"ok": True})]++ result = cursor._fetch(session, "POST", "https://api.cursor.com/teams/spend", mock.Mock())++ assert result == {"ok": True}+ assert session.request.call_count == 2++ def test_fetch_raises_on_client_error_without_retry(self):+ session = mock.Mock()+ session.request.return_value = _response(401)++ with pytest.raises(requests.HTTPError):+ cursor._fetch(session, "GET", "https://api.cursor.com/teams/members", mock.Mock())++ assert session.request.call_count == 1++ def test_unknown_endpoint_raises(self):+ with pytest.raises(ValueError, match="Unknown Cursor endpoint"):+ cursor_source("key_test", "audit_logs", mock.Mock(), _manager())++ @parameterized.expand(+ [+ ("members", ["id"], None),+ ("daily_usage", ["date", "userId"], ["date"]),+ ("usage_events", ["id"], ["timestamp"]),+ ("spend", ["userId"], None),+ ]+ )+ def test_source_response_shape(self, endpoint, primary_keys, partition_keys):+ response = cursor_source("key_test", endpoint, mock.Mock(), _manager())++ assert response.name == endpoint+ assert response.primary_keys == primary_keys+ assert response.partition_keys == partition_keys+ assert response.sort_mode == "asc"++ def test_members_yields_single_batch_via_get(self):+ session = mock.Mock()+ session.request.return_value = _response(200, {"teamMembers": [{"id": 1, "email": "[email protected]", "role": "owner"}]})++ with mock.patch.object(cursor, "make_tracked_session", return_value=session):+ batches = list(_batches(cursor_source("key_test", "members", mock.Mock(), _manager())))++ assert batches == [[{"id": 1, "email": "[email protected]", "role": "owner"}]]+ assert session.request.call_args.args[0] == "GET"+ assert session.request.call_args.args[1].endswith("/teams/members")++ def test_spend_paginates_and_stamps_cycle_start(self):+ manager = _manager()+ page_one = {+ "teamMemberSpend": [{"userId": i} for i in range(100)],+ "subscriptionCycleStart": 1_700_000_000_000,+ "totalPages": 2,+ }+ page_two = {+ "teamMemberSpend": [{"userId": 100}],+ "subscriptionCycleStart": 1_700_000_000_000,+ "totalPages": 2,+ }+ session = mock.Mock()+ session.request.side_effect = [_response(200, page_one), _response(200, page_two)]++ with mock.patch.object(cursor, "make_tracked_session", return_value=session):+ batches = list(_batches(cursor_source("key_test", "spend", mock.Mock(), manager)))++ assert [len(batch) for batch in batches] == [100, 1]+ assert all(row["subscriptionCycleStart"] == 1_700_000_000_000 for batch in batches for row in batch)+ assert session.request.call_args_list[0].kwargs["json"]["page"] == 1+ assert session.request.call_args_list[1].kwargs["json"]["page"] == 2+ # State was saved after the non-final page so a retry resumes at page 2.+ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0].page == 2++ def test_spend_resumes_from_saved_page(self):+ manager = _manager(CursorResumeConfig(page=3))+ session = mock.Mock()+ session.request.return_value = _response(200, {"teamMemberSpend": [{"userId": 7}], "totalPages": 3})++ with mock.patch.object(cursor, "make_tracked_session", return_value=session):+ batches = list(_batches(cursor_source("key_test", "spend", mock.Mock(), manager)))++ assert len(batches) == 1+ assert session.request.call_args.kwargs["json"]["page"] == 3++ def test_windowed_first_sync_starts_at_lookback(self):+ now_ms = 1_700_000_000_000+ session = mock.Mock()+ session.request.return_value = _response(200, {"usageEvents": [], "pagination": {"hasNextPage": False}})++ with (+ mock.patch.object(cursor, "_now_ms", return_value=now_ms),+ mock.patch.object(cursor, "make_tracked_session", return_value=session),+ ):+ list(_batches(cursor_source("key_test", "usage_events", mock.Mock(), _manager())))++ first_body = session.request.call_args_list[0].kwargs["json"]+ assert first_body["startDate"] == now_ms - cursor.DEFAULT_LOOKBACK_DAYS * DAY_MS+ assert first_body["endDate"] == first_body["startDate"] + WINDOW_MS - 1+ # The whole lookback is covered in <=30-day chunks.+ expected_requests = -(-cursor.DEFAULT_LOOKBACK_DAYS * DAY_MS // WINDOW_MS)+ assert session.request.call_count == expected_requests++ def test_windowed_incremental_starts_at_watermark(self):+ now_ms = 1_700_000_000_000+ watermark = datetime.fromtimestamp((now_ms - 5 * DAY_MS) / 1000, tz=UTC)+ session = mock.Mock()+ session.request.return_value = _response(200, {"usageEvents": [], "pagination": {"hasNextPage": False}})++ with (+ mock.patch.object(cursor, "_now_ms", return_value=now_ms),+ mock.patch.object(cursor, "make_tracked_session", return_value=session),+ ):+ list(+ _batches(+ cursor_source(+ "key_test",+ "usage_events",+ mock.Mock(),+ _manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ )+ )+ )++ assert session.request.call_count == 1+ body = session.request.call_args.kwargs["json"]+ assert body["startDate"] == now_ms - 5 * DAY_MS+ assert body["endDate"] == now_ms++ def test_windowed_resumes_from_saved_window_and_page(self):+ now_ms = 1_700_000_000_000+ window_start = now_ms - 10 * DAY_MS+ manager = _manager(CursorResumeConfig(window_start=window_start, page=4))+ session = mock.Mock()+ session.request.return_value = _response(200, {"usageEvents": [], "pagination": {"hasNextPage": False}})++ with (+ mock.patch.object(cursor, "_now_ms", return_value=now_ms),+ mock.patch.object(cursor, "make_tracked_session", return_value=session),+ ):+ list(_batches(cursor_source("key_test", "usage_events", mock.Mock(), manager)))++ body = session.request.call_args.kwargs["json"]+ assert body["startDate"] == window_start+ assert body["page"] == 4++ def test_windowed_saves_state_after_each_batch(self):+ now_ms = 1_700_000_000_000+ manager = _manager()+ pages = [+ _response(+ 200,+ {+ "usageEvents": [{"timestamp": str(now_ms - 1), "userEmail": "[email protected]"}],+ "pagination": {"hasNextPage": True},+ },+ ),+ _response(+ 200,+ {+ "usageEvents": [{"timestamp": str(now_ms), "userEmail": "[email protected]"}],+ "pagination": {"hasNextPage": False},+ },+ ),+ ]+ session = mock.Mock()+ session.request.side_effect = pages++ with (+ mock.patch.object(cursor, "_now_ms", return_value=now_ms),+ mock.patch.object(cursor, "make_tracked_session", return_value=session),+ ):+ # A recent watermark keeps the sync to a single window so both mocked pages belong to it.+ source = cursor_source(+ "key_test",+ "usage_events",+ mock.Mock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime.fromtimestamp((now_ms - 10 * DAY_MS) / 1000, tz=UTC),+ )+ iterator = _batches(source)++ first_batch = next(iterator)+ assert first_batch[0]["id"] # synthetic primary key was added+ # The generator is suspended at the yield — nothing saved until the consumer has+ # taken the batch and pulls the next one, so a crash mid-batch re-fetches it.+ assert manager.save_state.call_count == 0++ next(iterator)+ # Resuming past the first yield saved a bookmark at page 2 of the same window.+ saved = manager.save_state.call_args.args[0]+ assert saved.page == 2+ assert saved.window_start is not None++ list(iterator)++ assert session.request.call_count == 2+ assert session.request.call_args_list[1].kwargs["json"]["page"] == 2diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/tests/test_cursor_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/tests/test_cursor_source.pynew file mode 100644index 000000000000..7b83869854c0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/tests/test_cursor_source.py@@ -0,0 +1,143 @@+from typing import Any++from unittest import mock++from parameterized import parameterized++from posthog.schema import (+ ExternalDataSourceType as SchemaExternalDataSourceType,+ SourceFieldInputConfig,+)++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.cursor.cursor import CursorResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.cursor.source import CursorSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CursorSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _make_inputs(**overrides) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": "usage_events",+ "schema_id": "schema-id",+ "source_id": "source-id",+ "team_id": 123,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-id",+ "logger": mock.Mock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestCursorSource:+ def setup_method(self):+ self.source = CursorSource()+ self.config = CursorSourceConfig(api_key="key_test")+ self.team_id = 123++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.CURSOR++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name == SchemaExternalDataSourceType.CURSOR+ assert config.label == "Cursor"+ assert config.unreleasedSource is True+ field = config.fields[0]+ assert isinstance(field, SourceFieldInputConfig)+ assert len(config.fields) == 1+ assert field.name == "api_key"+ assert field.required is True+ assert field.secret is True+ # The docs slug is derived from docsUrl; a mismatch 404s the public doc.+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/cursor"++ def test_get_schemas_returns_all_endpoints(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert [s.name for s in schemas] == ["members", "daily_usage", "usage_events", "spend"]+ assert all(s.should_sync_default for s in schemas)++ @parameterized.expand(+ [+ ("members", False, None),+ ("daily_usage", True, "date"),+ ("usage_events", True, "timestamp"),+ ("spend", False, None),+ ]+ )+ def test_get_schemas_incremental_support(self, endpoint, supports_incremental, incremental_field):+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ schema = schemas[endpoint]++ assert schema.supports_incremental is supports_incremental+ assert schema.supports_append is supports_incremental+ if incremental_field:+ assert [f["field"] for f in schema.incremental_fields] == [incremental_field]+ else:+ assert schema.incremental_fields == []++ def test_get_schemas_filters_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["members", "spend"])++ assert [s.name for s in schemas] == ["members", "spend"]++ def test_get_documented_tables_lists_endpoints_without_credentials(self):+ # lists_tables_without_credentials=True drives the public docs' Supported tables section.+ tables = self.source.get_documented_tables()++ assert [t["name"] for t in tables] == ["members", "daily_usage", "usage_events", "spend"]+ assert all(t["description"] for t in tables)++ @parameterized.expand([(True, (True, None)), (False, (False, "Invalid Cursor Admin API key"))])+ def test_validate_credentials(self, valid, expected):+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.cursor.source.validate_cursor_credentials",+ return_value=valid,+ ):+ assert self.source.validate_credentials(self.config, self.team_id) == expected++ @parameterized.expand([("401 Client Error",), ("403 Client Error",)])+ def test_non_retryable_errors_cover_credential_failures(self, status):+ keys = self.source.get_non_retryable_errors()+ assert any(key.startswith(status) for key in keys)++ def test_get_resumable_source_manager_bound_to_resume_config(self):+ manager = self.source.get_resumable_source_manager(_make_inputs())++ assert manager._data_class is CursorResumeConfig++ @parameterized.expand(+ [+ (True, 1700000000000, 1700000000000),+ # A stale watermark must not leak into a full-refresh run.+ (False, 1700000000000, None),+ ]+ )+ def test_source_for_pipeline_plumbs_arguments(self, should_use_incremental_field, last_value, expected_last_value):+ inputs = _make_inputs(+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=last_value,+ )+ manager = mock.Mock()++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.cursor.source.cursor_source"+ ) as mock_source:+ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once_with(+ api_key="key_test",+ endpoint="usage_events",+ logger=inputs.logger,+ resumable_source_manager=manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=expected_last_value,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex c3e293f62a67..bc6c78ec1f3e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -952,7 +952,7 @@ class CultureAmpSourceConfig(config.Config):@config.configclass CursorSourceConfig(config.Config):- pass+ api_key: str@config.config