-
Notifications
You must be signed in to change notification settings - Fork 38
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
(PC-31961)[API] feat: Delete offers description when linked to a product #14249
Open
mageoffray
wants to merge
1
commit into
master
Choose a base branch
from
mageoffray/pc-31961-script-delete-description
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
import argparse | ||
import datetime | ||
import logging | ||
import math | ||
import statistics | ||
import time | ||
|
||
import pytz | ||
from sqlalchemy import func | ||
from sqlalchemy import text | ||
|
||
import pcapi.core.offers.models as offers_models | ||
from pcapi.models import db | ||
|
||
|
||
logger = logging.getLogger(__name__) | ||
|
||
BATCH_SIZE = 1_000 | ||
REPORT_EVERY = 1_000 | ||
|
||
|
||
def _get_eta(end: int, current: int, elapsed_per_batch: list[int]) -> str: | ||
left_to_do = end - current | ||
seconds_eta = left_to_do / BATCH_SIZE * statistics.mean(elapsed_per_batch) | ||
eta = datetime.datetime.utcnow() + datetime.timedelta(seconds=seconds_eta) | ||
eta = eta.astimezone(pytz.timezone("Europe/Paris")) | ||
str_eta = eta.strftime("%d/%m/%Y %H:%M:%S") | ||
return str_eta | ||
|
||
|
||
def delete_description(starting_id: int, ending_id: int, not_dry: bool = False) -> None: | ||
max_id = db.session.query(func.max(offers_models.Offer.id)).scalar() | ||
vacuum_treshold = int(max_id * 0.19) | ||
vacuum_treshold_rounded = math.ceil(vacuum_treshold / 1000) * 1000 | ||
logger.info("Run a vacuum every %s offers", vacuum_treshold) | ||
elapsed_per_batch = [] | ||
to_report = 0 | ||
for i in range(starting_id, ending_id, BATCH_SIZE): | ||
start_time = time.perf_counter() | ||
db.session.execute( | ||
""" | ||
update offer set "description" = null | ||
where id between :start and :end and "productId" is not null | ||
""", | ||
params={"start": i, "end": i + BATCH_SIZE}, | ||
) | ||
if not_dry: | ||
db.session.commit() | ||
if i % vacuum_treshold_rounded == 0: | ||
start_maintenance_time = time.perf_counter() | ||
# VACUUM must run outside a transaction context. | ||
# This is the only way i could make it work | ||
logger.info("Starting vacuum and analyze offers") | ||
db.session.execute(text("COMMIT")) | ||
db.session.execute(text("VACUUM offer")) | ||
db.session.execute(text("ANALYZE offer")) | ||
logger.info("Ending vacuum and analyze offers - %s", int(time.perf_counter() - start_maintenance_time)) | ||
else: | ||
db.session.rollback() | ||
elapsed_per_batch.append(int(time.perf_counter() - start_time)) | ||
eta = _get_eta(ending_id, starting_id, elapsed_per_batch) | ||
to_report += BATCH_SIZE | ||
if to_report >= REPORT_EVERY: | ||
to_report = 0 | ||
logger.info("BATCH : id from %s | eta = %s", i, eta) | ||
|
||
|
||
if __name__ == "__main__": | ||
from pcapi.flask_app import app | ||
|
||
app.app_context().push() | ||
|
||
parser = argparse.ArgumentParser(description="Delete description for offers linked to a product") | ||
parser.add_argument("--starting-id", type=int, default=0, help="starting offer id") | ||
parser.add_argument("--ending-id", type=int, default=0, help="ending offer id") | ||
parser.add_argument("--not-dry", action="store_true", help="set to really process (dry-run by default)") | ||
args = parser.parse_args() | ||
|
||
if args.starting_id > args.ending_id: | ||
raise ValueError('"start" must be less than "end"') | ||
|
||
delete_description(args.starting_id, args.ending_id, args.not_dry) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Prenons le cas ou le k*batch size+ starting_id ne tombe jamais sur un mutliple de vacccum_treshold(qui est fixe) avec un interval très important entre start et end et un un start> vacumm_treshold. on ne va pas faire de vaccum même si on traite un vaccum_treshold nombre de lignes.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes en effet, je m'étais dis ça et j'ai ajouté un arrondi pour tomber toujours sur un multiple de 1000.
Mais au final comme j'ai fais un lot qui commence à 1, i vaudra toujours 1, 1001, 2001, ... Et sera jamais un multiple de vacuum_treshold_rounded.
Faut que j'améliore le truc, merci 🙏